问题:
难度:easy
说明:
找到到达二叉树子叶的最短路径,子叶是没有子节点的节点,节点值似乎没什么用。
问题链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/
输入案例:
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
我的代码:
用递归做一遍,dfs 效率比较低。
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int left = minDepth(root.left), right = minDepth(root.right);
if(left == 0 && right == 0) return 1;
if(left == 0) return right + 1;
if(right == 0) return left + 1;
return Math.min(left, right) + 1;
}
}
用循环做一遍,而且用 bfs 一遇到子叶就马上跳出就快多了
class Solution {
private static int begin = 0;
private static int end = 0;
private static TreeNode[] queue = new TreeNode[100000];
public int minDepth(TreeNode root) {
begin = 0;
end = 0;
if(root != null) queue[end ++] = root;
int min = 0;
while(end != begin) {
int e = end;
for(;begin < e;) {
TreeNode node = queue[begin ++];
if(node.left == null && node.right == null) return min + 1;
if(node.left != null) queue[end ++] = node.left;
if(node.right != null) queue[end ++] = node.right;
}
min ++;
}
return min;
}
}