您的位置:首页 > 其它

Leetcode - Minimum Depth of Binary Tree

2016-04-19 21:11 267 查看

Question

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.

Java Code

public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

//版本一: DFS,递归遍历每一个节点,取根节点到所有叶子节点距离的最小值
public int minDepth(TreeNode root) {
if(root == null)
return 0;
else if(root.left != null && root.right != null)
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
else if(root.left != null && root.right == null)
return minDepth(root.left) + 1;
else if(root.left == null && root.right != null)
return minDepth(root.right) + 1;
else
return 1;
}

//版本二: BFS,逐层遍历,找到第一个叶子节点即结束
public int minDepth(TreeNode root) {
if(root == null)  return 0;
LinkedList<TreeNode> list = new LinkedList<>();

list.add(root);
list.add(null);

TreeNode temp;
int level = 0;

while(list.size() != 1) {
level++;
while ((temp = list.pollFirst()) != null) {
if(temp.left != null && temp.right != null) {
list.add(temp.left);
list.add(temp.right);
}else if(temp.left != null && temp.right == null)
list.add(temp.left);
else if(temp.left == null && temp.right != null)
list.add(temp.right);
else
return level;
}
list.add(null);
}

return level;
}


说明

版本一的代码可以参考另一个类似的题目Maximum Depth of Binary Tree,本题不能通过仅仅把Math.max函数改成Math.min来实现,因为本题求的是根节点与最近的叶子节点之间的距离,当二叉树中非叶子节点出现空子节点时,直接选择其左右子树中较小的深度就会出错(但直接选择其左右子树中较大的深度却不会出错,why?)

版本二的代码采取层次遍历的方法,这样可以尽快找到最先出现叶子节点的层,也即找到了树的最小深度,避免了继续遍历该层以下的节点,具体细节可以参考另一个类似的题目Binary Tree Level Order Traversal
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode DFS BFS depth