[Leetcode 10] 111 Minimum Depth of Binary Tree
Problem:
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.
Analysis:
This problem is quite easy. When we compute the height of a binary tree, we use 1 + max(left_height, right_height) recursivly. So the height of a binary tree is actually the maximum depth of this tree. So to get minimum depth, we change max to min to have the following formular 1 + min (left_height, right_height) computed recursively.
One problem here is that height must be the distance from root to leaf. This implies that the following two trees :[1 2] and [1 # 2] has the height of 2 rather than one. We need to omit those null leaf nodes while computing
Code:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int minDepth(TreeNode root) { 12 // Start typing your Java solution below 13 // DO NOT write main() function 14 if (root == null) 15 return 0; 16 else if (root.left==null && root.right==null) 17 return 1; 18 else if (root.left==null && root.right!=null) 19 return 1 + minDepth(root.right); 20 else if (root.left!=null && root.right==null) 21 return 1 + minDepth(root.left); 22 else 23 return 1 + min(minDepth(root.left), minDepth(root.right)); 24 } 25 26 private int min(int a, int b) { 27 return (a>b) ? b : a; 28 } 29 }
Attention:
The minimum depth of a binary tree must from root to some not-null leaf nodes. See the definition clearly.!