您的位置:首页 > 其它

LeetCode: Minimum Depth of Binary Tree 解题报告

2014-12-18 22:59 323 查看
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.

// SOLUTION 2:
// Level Traversal:
public int minDepth(TreeNode root) {
/*
主页君认为,在这应该是属于未定义行为,这里我们定义为MAX会比较好,因为
null就是取不到任何节点,没有path,不应该将最小值定为0.
*/
if (root == null) {
return 0;
}

int level = 0;

Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);

while (!q.isEmpty()) {
int size = q.size();
level++;
for (int i = 0; i < size; i++) {
TreeNode cur = q.poll();

if (cur.left == null && cur.right == null) {
return level;
}

if (cur.left != null) {
q.offer(cur.left);
}

if (cur.right != null) {
q.offer(cur.right);
}
}
}

return 0;
}


View Code
GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/MinDepth_1218_2014.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: