LeetCode@111_Minimum_Depth_of_Binary_Tree

来源:互联网 发布:网络歌手大赛活动方案 编辑:程序博客网 时间:2024/06/05 03:10

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;}}


原创粉丝点击