height tree code example
Example 1: find height of a tree
// finding height of a binary tree in c++.
int maxDepth(node* node)
{
if (node == NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth + 1);
else return(rDepth + 1);
}
}
Example 2: height of binary tree
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def height(root):
if root is None:
return 0
leftAns = height(root.left)
rightAns = height(root.right)
return max(leftAns, rightAns) + 1
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
print("Height of the binary tree is: " + str(height(root)))