We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Interesting how most Java solutions subtract, mine does not (don't think it's better, simply different). Of course it uses more if's. Also, IMHO Math.max() is overkill for just two values.

public static int height(Node root) {
int leftHeight = 0;
int rightHeight = 0;
if (root.left != null) {
leftHeight = 1 + height(root.left);
}
if (root.right != null) {
rightHeight = 1 + height(root.right);
}
return leftHeight > rightHeight ? leftHeight : rightHeight;
}

Thanks for this! Borrowed and did a little adjustments in Python. When I did it, I didn't distinguish between left and right nodes for the height. Even if there are both left and right nodes for root, the return value will always be 1 or 0 when passed back up:

Even though your solution somehow passed all of the cases, I think your solution is incorrect. If you try input as: 4 3 4 2 1, your output will be 1, but the correct answer is 2.

## Tree: Height of a Binary Tree

You are viewing a single comment's thread. Return to all comments →

Interesting how most Java solutions subtract, mine does not (don't think it's better, simply different). Of course it uses more if's. Also, IMHO Math.max() is overkill for just two values.

Thanks for this! Borrowed and did a little adjustments in Python. When I did it, I didn't distinguish between left and right nodes for the height. Even if there are both left and right nodes for root, the return value will always be 1 or 0 when passed back up:

Even though your solution somehow passed all of the cases, I think your solution is incorrect. If you try input as: 4 3 4 2 1, your output will be 1, but the correct answer is 2.

To put it in other words, this solution will only return height of the right branch and override the calculations done on the left branch.

static int height(Node root) { if(root==null) return -1; else return height(root.left)>height(root.right)? 1+height(root.left) : 1+height(root.right); }

This works better.

can you can expalin the working & how the recursion will work in the program.