How to find height of binary tree
Max height is computed by taking the longest height of any sub tree starting from root node. The logic is to iterate through either left sub tree or right subtree and consider the longer height and further iterate to that sub tree till we reach the leaf. This way we can obtain the maximum depth/height of a binary tree.
The height of a binary tree is found using the recursive Depth-First Search (DFS) algorithm, as shown below:
- Base case: If there is no node, return 0.
- Else: If there are 1 or 2 children, return the maximum of the height of the left and right sub-trees, plus 1 to account for the current node. The height of a sub-tree is found by recursively calling the function, and passing the child node as the parameter.
No comments:
Post a Comment