102.Binary Tree Level Order Traversal (M)

https://leetcode.com/problems/binary-tree-level-order-traversal/

1.Description(Easy)

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Example

Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

2.Code

加一个size记录每一层的Node个数,每次遍历完这一层的时候queue里只剩下上一层的子节点们。

public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root){
    ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
    if(root==null){
        return result;
    }

    LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
    queue.offer(root);
    while(!queue.isEmpty()){
        ArrayList<Integer> level=new ArrayList<Integer>();
        int size=queue.size();
        for(int i=0;i<size;i++){

            TreeNode current=queue.poll();
            level.add(current.val);
            if(current.left!=null){
                queue.offer(current.left);
            }
            if(current.right!=null){
                queue.offer(current.right);
            }
        }
            result.add(level);
    }
        return result;
}

Last updated