描述
请根据二叉树的前序遍历,中序遍历恢复二叉树,并打印出二叉树的右视图
示例1
输入:
[1,2,4,5,3],[4,2,5,1,3]
复制返回值:
[1,3,5]
复制
备注:
二叉树每个节点的值在区间[1,10000]内,且保证每个节点的值互不相同。
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 求二叉树的右视图
# @param xianxu int整型一维数组 先序遍历
# @param zhongxu int整型一维数组 中序遍历
# @return int整型一维数组
#
class Solution:
def solve(self , xianxu , zhongxu):
def buildtree(xianxu,zhongxu):
if not xianxu or not zhongxu:
return None
root = TreeNode(xianxu.pop(0))
idx = zhongxu.index(root.val)
root.left = buildtree(xianxu,zhongxu[:idx])
root.right = buildtree(xianxu,zhongxu[idx+1:])
return root
root = buildtree(xianxu,zhongxu)
stack = [root]
flag = 1
res = [root.val]
while stack:
cur = stack.pop(0)
flag -= 1
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
if flag == 0:
if stack:
res.append(stack[-1].val)
flag = len(stack)
return res
# write code here
前序:3 9 8 5 4 10 20 15 7
中序:4 5 8 10 9 3 15 20 7
1. 前序第一个为根节点
2. 找到中序中根节点的位置,左边为左子树,右边为右子树
3. root.left = BFS(xianxu, zhongxu[:idx])递归查找左子树根节点
4. root.right = BFS (xianxu, zhongxu[idx:]) 递归查找右子树根节点
根据前序和中序递归重建二叉树完成
层序遍历:
根节点入栈,为第一层。
根节点出栈,所有子节点入栈,为第二层。
第二层所有子节点依次出栈,同时使其对应的孙子节点入栈,形成第三层。
如此循环即可。