您的位置:首页 > 其它

leetcode 111.Minimum Depth of Binary Tree-树最小深度|深度遍历|广度遍历

2016-04-26 23:39 441 查看
原题链接:111.Minimum Depth of Binary Tree
【思路】

采用 dfs深度优先:

public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left != null && root.right != null)  //当根左右均不为空时,遍历左右子树,取最小值
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
return Math.max(minDepth(root.left), minDepth(root.right)) + 1;  //当左右子树有一边为空时,要去最大值
}
41 / 41 test
cases passed. Runtime: 1
ms Your runtime beats 12.17% of javasubmissions.

【补充】

采用 bfs 非递归实现:

public int minDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int layer = 1;
queue.add(root);
while (!queue.isEmpty()) {
int curCount = queue.size();  //本层节点数
while (curCount-- > 0) {  //将下一层节点存入 queue 中
TreeNode temp = queue.poll();
if (temp.left == null && temp.right == null) return layer;
if (temp.left != null) queue.add(temp.left);
if (temp.right != null) queue.add(temp.right);
}
layer++;
}
return layer;
}
41 / 41 test
cases passed. Runtime: 1 ms Your runtime beats 12.17% of javasubmissions.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: