`
blue2048
  • 浏览: 178191 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

[leetcode]Minimum Depth of Binary Tree-java 广度遍历

阅读更多
/**

 * Definition for binary tree

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

        }

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();

        LinkedList<TreeNode> childQueue = new LinkedList<TreeNode>();

        queue.add(root);

        int depth = 1;

        while (!queue.isEmpty()){

            TreeNode node = queue.remove();

            if(node.left==null && node.right==null){

                return depth;

            }

            if(node.left!=null){

                childQueue.add(node.left);

            }

            if(node.right!=null){

                childQueue.add(node.right);

            }

            if(queue.isEmpty() && !childQueue.isEmpty()){

                depth++;

                queue.addAll(childQueue);

                childQueue.clear();

            }

        }

        return depth;

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics