104/111 Maximum/Minimum Depth of Binary Tree
**104 Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.**
- If tree is empty then return 0
- Else (a) Get the max depth of left subtree recursively i.e.,
(a) Get the max depth of right subtree recursively i.e.,call maxDepth( tree->left-subtree)
(c) Get the max of max depths of left and rightcall maxDepth( tree->right-subtree)
(d) Return max_depthsubtrees and add 1 to it for the current node. max_depth = max(max dept of left subtree, max depth of right subtree) + 1
public int maxDepth(TreeNode root) {
if(root == null)
{
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
111 Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
NOTE!: Note that the path must end on a leaf node. For example, minimum height of below Binary Tree is also 2.
10
/
5
public int minDepth(TreeNode root) {
if(root == null)
{
return 0;
}
int leftMin = minDepth(root.left);
int rightMin = minDepth(root.right);
/*
* Base case: Leaf node, count the fepth as 1
*/
if(leftMin==0 && rightMin==0)
{
return 1;
}
/*
* When left subtree is null
*/
if(root.left == null)
{
return 1+rightMin;
}
/* When right subtree is null
*/
if(root.right == null)
{
return 1+leftMin;
}
return 1 + Math.min(leftMin, rightMin);
}