Search code examples
c#binary-tree

How can I correctly traverse a binary tree in order to return the height of it?


I have started implementing this code but now I'm stuck. I'm trying to return the height of the tree from the root to the furthest leaf. I'm able to access the outside leaves but not the inner ones. How can I incorporate the inner leaves in my function in order to return the highest height?

static int getHeight(Node root){
  int left = 0;
  int right = 0;
  Node head = root;
  while(root.left != null) {
      root = root.left;
      left++;
  }
  while(head.right != null) {
      head = head.right;
      right++;
  }
return Math.Max(left, right);

Solution

  • try this recursive algorithm:

    static int getHeight(Node root){
        int left = 0;
        int right = 0;
        if(root==null) return 0
        left = getHeight(root.left)+1;
        right= getHeight(root.right)+1;
        return Math.Max(left, right);
    }