根據二叉樹的前序遍歷,中序遍歷恢復二叉樹,並打印出二叉樹的右檢視
阿新 • • 發佈:2021-07-16
題目描述:
請根據二叉樹的前序遍歷,中序遍歷恢復二叉樹,並打印出二叉樹的右檢視
示例1
輸入:
[1,2,4,5,3],[4,2,5,1,3]
返回值:
[1,3,5]
分析:
本題總體可拆分為兩部分:
① 根據先序、中序遍歷重構二叉樹
② 層序遍歷二叉樹輸出每層最右側元素
重構:
先序確定根節點,中序確定左右子樹;左右子樹又可以繼續拆分,繼續確定子樹的根節點及左右子;
右檢視:
原理同層序遍歷,廣度優先(bfs);佇列儲存結點,左先右後。list[-1]就是每一層最右側的節點;
程式碼:
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def solve(self, xianxu, zhongxu):
def treeRebuild(xianxu, zhongxu):
if not xianxu or not zhongxu:
return None
root = Node(xianxu[0])
ind = zhongxu.index(xianxu[0])
root.left = treeRebuild(xianxu[1:ind + 1], zhongxu[:ind])
root.right = treeRebuild(xianxu[ind + 1:], zhongxu[ind + 1:])
return root
root = treeRebuild(xianxu, zhongxu)
if not root:
return None
res = []
queue = []
queue.append(root)
while queue:
res.append(queue[-1].val)
length = len(queue)
for _ in range(length):
top = queue.pop(0)
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
return res
xianxu=[1,2,4,5,3]
zhongxu=[4,2,5,1,3]
s=Solution()
print(s.solve(xianxu,zhongxu))
[1, 3, 5]