题意
计算二叉树的最低深度
我的思路
我的代码
1 | int min = Integer.MAX_VALUE; |
大神代码
递归实现1
2
3
4
5
6
7
8
9public class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
}
}
非递归实现(效率很快)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18int minDepth(TreeNode* root) {
if (root == NULL) return 0;
queue<TreeNode*> Q;
Q.push(root);
int i = 0;
while (!Q.empty()) {
i++;
int k = Q.size();
for (int j=0; j<k; j++) {
TreeNode* rt = Q.front();
if (rt->left) Q.push(rt->left);
if (rt->right) Q.push(rt->right);
Q.pop();
if (rt->left==NULL && rt->right==NULL) return i;
}
}
return -1; //For the compiler thing. The code never runs here.
}