原题
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
Reference Answer
解题思路:
思路:用一个临时数组存储需要打印的节点,如打印8时,将6和10存入临时数组
# -*- 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 []
temp = []
res = []
temp.append(root)
while temp:
temp_count = temp.pop(0)
res.append(temp_count.val)
if temp_count.left:
temp.append(temp_count.left)
if temp_count.right:
temp.append(temp_count.right)
return res
Note
这道题解题方式很巧妙,题目本意是一种二叉树遍历,但是若是想分层遍历,采用将下一轮结果存在temp
变量,每轮处理一轮,再加一轮,很巧妙。