【剑指offer】面试题32 - II. 从上到下打印二叉树 II

问题描述

面试题32 - II. 从上到下打印二叉树 II

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

分析

此题跟上一题相比较是把每一层单独存为一个数组了

因此要记录一下这一层有几个节点,然后遍历存一下。之前是一个一维的数据,现在是二维的

解题

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if(not root):
            return []
        res=[]
        temp=[root]
        
        while(temp):
            length = len(temp)
            a=[]
            for i in range(length):
                cur=temp.pop(0)
                a.append(cur.val)
                if(cur.left):
                    temp.append(cur.left)
                if(cur.right):
                    temp.append(cur.right)
            res.append(a)
        return(res)

猜你喜欢

转载自www.cnblogs.com/fuj905/p/12905688.html