题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

时间限制:1秒;空间限制:32768K

解题思路

思路和层次遍历相似,定义两个list一个用来记录当前层的节点,一个用来记录当前每个节点的左右孩子节点,循环打印更新。

Python代码:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
            return []
        currentStack = [] #当前层的节点
        currentStack.append(root)
        result = []
        while len(currentStack)!=0:
            nextStack = [] #下一层的子节点
            for i in range(len(currentStack)):
                result.append(currentStack[i].val)
                if currentStack[i].left != None:
                    nextStack.append(currentStack[i].left)
                if currentStack[i].right != None:
                    nextStack.append(currentStack[i].right)
            currentStack = nextStack
        return result

 

相关文章:

  • 2021-09-19
  • 2022-01-23
  • 2021-09-23
  • 2022-02-09
  • 2021-10-17
  • 2022-12-23
  • 2021-10-18
猜你喜欢
  • 2022-02-27
  • 2022-12-23
  • 2021-07-20
  • 2022-01-14
  • 2021-07-05
  • 2021-09-21
  • 2022-01-07
相关资源
相似解决方案