从上往下打印二叉树(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 #即层次遍历。使用列表res来存储遍历结点的值。 #再使用两个栈来存储当前层次的结点,以及下一层次的结点。 if root is None: return [] res = [] cur_stack = [root] while cur_stack: nxt_stack = [] for i in cur_stack: if i.left: nxt_stack.append(i.left) if i.right: nxt_stack.append(i.right) res.append(i.val) cur_stack = nxt_stack return res