LillianEom
6/19/2018 - 11:42 AM

二叉树的层序遍历

队列

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class BinaryTree {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        if(root != null) {
            queue.add(root);
        }
        while(queue.size()!=0) {
            int count = queue.size();
            List<Integer> level = new ArrayList<>();
            for(int i=0; i<count; i++) {    // 关键
                TreeNode node = queue.remove();
                level.add(node.val);
                if(node.left!=null) {
                    queue.add(node.left);
                }
                if(node.right!=null) {
                    queue.add(node.right);
                }
            }
            result.add(level);
        }       
        return result;
    }
}