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;
}
}
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;
}
}
相关文章推荐
- [leetcode111].Minimum Depth of Binary Tree
- LeetCode(111) Minimum Depth of Binary Tree
- Leetcode #111 Minimum Depth of Binary Tree
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- Leetcode 111, Minimum Depth of Binary Tree
- Java for LeetCode 111 Minimum Depth of Binary Tree
- LeetCode 111 Minimum Depth of Binary Tree (DFS)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- LeetCode(111)Minimum Depth of Binary Tree
- leetcode111——Minimum Depth of Binary Tree
- LeetCode 111 Minimum Depth of Binary Tree(二叉树的最短深度)(BT、DFS)(*)
- [leetcode 111] Minimum Depth of Binary Tree
- Leetcode#111 Minimum Depth of Binary Tree
- LeetCode-111-Minimum Depth of Binary Tree(二叉树的最短路径)
- [leetcode-111]Minimum Depth of Binary Tree(C语言)
- leetcode 111 —— Minimum Depth of Binary Tree
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [LeetCode]111 Minimum Depth of Binary Tree
- Leetcode[111]-Minimum Depth of Binary Tree
- [LeetCode#104, 111]Maximum Depth of Binary Tree, Minimum Depth of Binary Tree