[leetcode]Minimum Depth of Binary Tree-java広さ遍歴

1531 ワード

/**

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

    }

}