Skip to content
本页目录

32-II-从上到下打印二叉树II

题目描述

https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof

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

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

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

提示:

节点总数 <= 1000 注意:本题与主站 102 题相同:https://leetcode.cn/problems/binary-tree-level-order-traversal/

思路分析

注意每次压入 queue 的时候, 第二次循环,先取出当前 queue 的 count, 此时count之内的内容,都是在同一行的

实现代码

csharp
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList<IList<int>> LevelOrder(TreeNode root) {
        IList<IList<int>> arr = new List<IList<int>>();
        Queue<TreeNode> myQueue = new Queue<TreeNode>();
        List<int> row = new List<int>();
        int lineIndex = 1;
        if(root != null){
            myQueue.Enqueue(root);
            while(myQueue.Count > 0){
                //此时 queue 里面的都是同一行
                int count = myQueue.Count;
                row = new List<int>();
                //循环取出该行
                //注意这里循环了 count 非常重要
                for(int i=0; i<count; i++){
                    TreeNode node = myQueue.Dequeue();
                    row.Add(node.val);
                    if(node.left != null){
                        myQueue.Enqueue(node.left);
                    }
                    if(node.right != null){
                        myQueue.Enqueue(node.right);
                    }
                }
                arr.Add(row);
            }
        }
        return arr;
    }
}

Released under the MIT License.