题目:
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.
题解:
递归解法急速判断左右两边子树哪个depth最小,要注意如果有个节点只有一边孩子时,不能返回0,要返回另外一半边的depth。
递归解法:
1 public class Solution { 2 public int minDepth(TreeNode root) 3 { 4 int depth=0; 5 depth=depthHelper(root,depth); 6 return depth; 7 } 8 9 public int depthHelper(TreeNode root, int depth) 10 { 11 if(root==null) 12 return 0; 13 14 depth+=1; 15 if(root.left!=null&&root.right!=null) 16 { 17 return Math.min(depthHelper(root.left,depth),depthHelper(root.right,depth)); 18 } 19 else if (root.left==null&&root.right!=null) 20 { 21 return depthHelper(root.right,depth); 22 } 23 else if(root.left!=null&&root.right==null) 24 { 25 return depthHelper(root.left,depth); 26 } 27 else return depth; 28 29 } 30 }
解法二:
public class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } return getMin(root); } public int getMin(TreeNode root){ if (root == null) { return Integer.MAX_VALUE; } if (root.left == null && root.right == null) { return 1; } return Math.min(getMin(root.left), getMin(root.right)) + 1; } }