Thursday, June 4, 2015

Future training - TreeHeight

Here is another codility problem solution from the codility lessons (TreeHeight -Compute the height of a binary tree.) due to the copy rights I can't copy the content of the problem here so to view the problem description click here.




// you can also use imports, for example:
// import java.util.*;

// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
 public int solution(Tree T) {
                // to remove the first node from the calculation
  return computeTreeHeight(T) - 1;
 }

 private int computeTreeHeight(Tree T) {
  if (T == null) return 0;
  int leftT = 1 + computeTreeHeight(T.l);
  int rightT = 1 + computeTreeHeight(T.r);

  return Math.max(rightT, leftT);
 }
}

No comments:

Post a Comment