剑指 Offer 32 - II. 从上到下打印二叉树 II

题目:从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

例如:给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

Reference:力扣(LeetCode),https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
解答:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List> levelOrder(TreeNode root) {
        Queue queue = new LinkedList<>();
        List> arr = new ArrayList<>();
        queue.offer(root);
        if (root == null){
            return arr;
        }
        while(!queue.isEmpty()){
            //记录每层的值得数组
            ArrayList level = new ArrayList<>();
            //记录每层的节点个数
            int num = queue.size();
            //每个节点遍历
            for (int i=0;i

你可能感兴趣的:(剑指 Offer 32 - II. 从上到下打印二叉树 II)