zoukankan      html  css  js  c++  java
  • 【剑指offer】面试题32

    问题描述

    面试题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)
  • 相关阅读:
    1001.A+B Format(20)
    大一下学期的自我目标
    re模块3
    re模块2
    re模块
    configParser模块
    logging模块
    hashlib模块
    sys模块
    isinstance函数
  • 原文地址:https://www.cnblogs.com/fuj905/p/12905688.html
Copyright © 2011-2022 走看看