原题链接在这里:https://leetcode.com/problems/minimum-depth-of-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.
题解:
与Maximum Depth of Binary Tree相似。
不同是多了判断叶子节点,若是给出[1,2]这种情况,返回值应该是2而不是1, 即使root的右节点为空,但根据定义:The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 此时root.left不为null, 所以root不能被认为是leaf. 因此加了if(root.left == null) return right+1, 这里注意加一。
Time Complexity: O(n)最坏的情况每个节点走了一遍. Space: O(logn), recursion stack 是 tree 的高度是logn.
AC Java:
1 /** 2 * Definition for a binary tree node. 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 if(root == null){ 13 return 0; 14 } 15 16 int left = minDepth(root.left); 17 int right = minDepth(root.right); 18 19 if(root.left == null){ 20 return right+1; 21 } 22 if(root.right == null){ 23 return left+1; 24 } 25 26 return Math.min(left, right)+1; 27 } 28 }