[LeetCode]102. 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).
//按层遍历二叉树,返回二位数组,null值跳过。
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]
]

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root == null ) return list;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        int level = 0;
        while(!queue.isEmpty()){
            level = queue.size(); //相同层的值放入一个数组里,需要记录当前层包含多少个值
            List<Integer> subList = new ArrayList<>();
            for(int i=0; i< level; i++){
                TreeNode node = queue.poll();
                subList.add(node.val);//循环将相同层的值放入同一个数组
                if(node.left != null){
                    queue.offer(node.left);   
                }
                if(node.right != null){
                    queue.offer(node.right); 
                }
            }
            list.add(subList);              
        }
        return list;  
    }
}

你可能感兴趣的:(算法与数据结构)