【剑指Offer】22从上往下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
时间限制: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