111. Minimum Depth of Binary Tree
Description:
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: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its minimum depth = 2.
Find Minimum Depth of a Binary Tree
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.
For example, minimum height of below Binary Tree is 2.
Note that the path must end on a leaf node. For example, the minimum height of below Binary Tree is also 2.
10 / 5
The idea is to traverse the given Binary Tree. For every node, check if it is a leaf node. If yes, then return 1. If not leaf node then if the left subtree is NULL, then recur for the right subtree. And if the right subtree is NULL, then recur for the left subtree. If both left and right subtrees are not NULL, then take the minimum of two heights.
Below is implementation of the above idea.
Solution:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int minDepth(TreeNode root) { return minHelper(root); } public int minHelper(TreeNode T){ if(T==null){ return 0; } if(T.left==null &&T.right==null){ return 1; } if(T.left ==null){ return minHelper(T.right)+1; } if(T.right == null){ return minHelper(T.left)+1; } return Math.min(minHelper(T.left), minHelper(T.right))+1; } }