Finding the max depth of the binary tree
Max depth: The maximum depth of a binary tree is the number of nodes from the root down to the furthest leaf node.
e.g:
MAX DEPTH = MAX(height of left subtree, height of right subtree)
As per the above image, Height of left subtree = 4 (i.e nodes 2,7,6,11)
and Height of right subtree= 4 (i.e nodes 2,5,9,4)
Therefore,MAX DEPTH = 4 ( as here height of LST and RST is same)
ALGORITHIM:
- Recursively find the height of LST.
- Recursively find the height of RST.
- Return the max among them.
JAVA CODE:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int maxDepth(TreeNode root) {
int height = maxHeight(root);
return height;
}
public int maxHeight(TreeNode root){
if(root == null){
return 0;
}
int ans = 0;
int left = maxHeight(root.left);
int right = maxHeight(root.right);
if(left > right){
return left+1;
}
else{
return right+1;
}
}
}