題目描述
知識點:二叉樹,層次遍歷
層次遍歷:
二叉樹的層次遍歷,需要藉助隊列,根節點入隊,每打印一個節點,一個節點出隊,並將其左右子樹入隊,直到隊列爲空
# -*- 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 # 下一層