问题分解:
- 将先序遍历和中序遍历还原成二叉树
- 将二叉树进行层序遍历,每次输出最右边的节点
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 求二叉树的右视图
# @param xianxu int整型一维数组 先序遍历
# @param zhongxu int整型一维数组 中序遍历
# @return int整型一维数组
#
import queue
class Solution:
def solve(self , xianxu: List[int], zhongxu: List[int]) -> List[int]:
# write code here
# 右视图即为每层最右边的节点
# 利用层序遍历来实现
# 先重构二叉树
root = self.reConstructBinaryTree(xianxu, zhongxu)
# 再进行层序遍历,输出最右边的元素
return self.levelRightTraverse(root)
def levelRightTraverse(self, root: TreeNode) -> List[int]:
if not root:
return []
q = queue.Queue()
q.put(root)
res = []
while not q.empty():
len_q = q.qsize()
for i in range(len_q):
temp = q.get()
if i == len_q - 1:
res.append(temp.val)
if temp.left:
q.put(temp.left)
if temp.right:
q.put(temp.right)
return res
def reConstructBinaryTree(self , pre: List[int], vin: List[int]) -> TreeNode:
# write code here
if not pre and not vin:
return None
else:
head_val = pre[0]
head = TreeNode(head_val)
index = vin.index(head_val)
head.left = self.reConstructBinaryTree(pre[1:(index + 1)], vin[:index])
head.right = self.reConstructBinaryTree(pre[(index + 1):], vin[(index + 1):])
return head