Input:
Binary Tree:1/\23/\45Node: 2Output:
2Explanation:
The subtree rooted at node 2 has two levels(edges from 2 to 4 and from 4 to 5). The longest path from node 2 to a leaf consists of 2 edges.
Input:
Binary Tree:1/\23Node: 1Output:
2Explanation:
The longest path from node 1 to a leaf passes through node 2 and ends at node 4 or node 5, both of which are on level 2.
Input:
Binary Tree:1/\23/4Node: 1Output:
2Explanation:
The longest path from node 1 to a leaf passes through node 2 and ends at node 4. In thiscase, there are two edges from node 1 to node 4, so the height is2.
The height of a node in a binary tree can be calculated recursively:
If the node is a leaf (no children), its height is 0.
Else, the height of the node is 1 + max(height of left child, height of right child).
This recursive relation allows us to break the problem into smaller subproblems where the height of a node is determined based on the height of its children.