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

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

1.解题思路

层次遍历二叉树,我们采用队列,本题的注意点是需要分割出每一层的序列,所以在从队列中取元素之前,我们要先记录队列的大小,以表示这一层中节点的个数。

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        if(root==null) return res;
        Queue<TreeNode> q=new LinkedList<TreeNode>();
        q.offer(root);
        int count=0;
        while(q.peek()!=null){
            count=q.size();
            List<Integer> subres=new ArrayList<Integer>();
           for(int i=0;i<count;i++){
                TreeNode node=q.poll();
                subres.add(node.val);
                if(node.left!=null)
                  q.offer(node.left);
                if(node.right!=null)
                  q.offer(node.right);
           }
        
            res.add(subres);
        }
        return res;
       
    
    }
}

tiffanytown
6 声望2 粉丝

keep learning