题目描述
知识点:二叉树,层次遍历
层次遍历:
二叉树的层次遍历,需要借助队列,根节点入队,每打印一个节点,一个节点出队,并将其左右子树入队,直到队列为空
# -*- 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 []
assert isinstance(root, TreeNode)
queue = []
result = []
queue.append(root)
while queue:
current_root = queue.pop(0)
result.append(current_root.val)
if current_root.left:
queue.append(current_root.left)
if current_root.right:
queue.append(current_root.right)
print(result)
分层输出:
思路同上,但需两个变量,
记录当前层还有几个节点未打印,每打印一个,值减一
下一层有几个节点,每入队一个节点加一
def PrintFromTopToBottom2(self, root):
# 分层打印
if not root:
return None
assert isinstance(root, TreeNode)
queue = []
queue.append(root)
n_node = 1 # 第n层还有几个结点没打印
next_n_node = 0 # 下一层结点数量
while queue:
current_root = queue.pop(0)
print(current_root.val, end=' ') # 不换行
n_node -= 1
if current_root.left:
next_n_node += 1
queue.append(current_root.left)
if current_root.right:
next_n_node += 1
queue.append(current_root.right)
if n_node == 0:
print() # 一层打印完毕,换行
n_node = next_n_node
next_n_node = 0
Z字型打印:
即蛇形打印,经分析,第一层为根节点,第二层从右向左打印,第三层从左向右打印,由此,借助两个栈
- 遍历奇数行时,子节点自左向右压入Stack2
- 遍历偶数行时,子节点自右向左压入Stack1
同上需要两个变量记录
def PrintFromTopToBottom3(self, root):
# Z字打印
if not root:
return None
assert isinstance(root, TreeNode)
stack1 = [] # 从左向右打印子节点,右节点先入栈,偶数行
stack2 = [] # 从右向左打印子节点,左节点先入栈,奇数行
stack2.append(root)
n = 1
n_node = 1 # 第n层还有几个结点没打印
next_n_node = 0 # 下一层结点数量
while stack1 or stack2:
if n & 0x1 == 1: # 奇数层,先左后右
current_root = stack2.pop()
if current_root.left:
stack1.append(current_root.left)
next_n_node += 1
if current_root.right:
stack1.append(current_root.right)
next_n_node += 1
elif n & 0x1 == 0: # 偶数层,先右后左
current_root = stack1.pop()
if current_root.right:
stack2.append(current_root.right)
next_n_node += 1
if current_root.left:
stack2.append(current_root.left)
next_n_node += 1
print(current_root.val, end=' ')
n_node -= 1
if n_node == 0:
print()
n_node = next_n_node
next_n_node = 0
n += 1 # 下一层