您的位置:首页 > 其它

LeetCode@111_Minimum_Depth_of_Binary_Tree

2017-06-29 11:28 357 查看
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:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public int minDepth(TreeNode root)
{
if (root == null)
return 0;

Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> depth = new LinkedList<>();
queue.add(root);
depth.add(1);

while (!queue.isEmpty())
{
TreeNode currNode = queue.poll();
int currDepth = depth.poll();

if (currNode.left != null)
{
queue.add(currNode.left);
depth.add(currDepth+1);
}
if (currNode.right != null)
{
queue.add(currNode.right);
depth.add(currDepth+1);
}

if (currNode.left == null && currNode.right == null)
{
return currDepth;
}
}

return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: