1递归构建二叉树。参考 https://www.cnblogs.com/xinchrome/p/4905608.html。
2使用python的字典储存深度上最右侧结点的数据,按顺序返回值(可以使用有序字典)。
运行结果 运行时间 占用内存 使用语言
答案正确 28ms 6520KB Python 3
dic = {}
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 求二叉树的右视图
# @param xianxu int整型一维数组 先序遍历
# @param zhongxu int整型一维数组 中序遍历
# @return int整型一维数组
#
class Solution:
def solve(self, xianxu, zhongxu):
# write code here
count = 0
recurve(xianxu, zhongxu, count)
global dic
i = 1
ans = []
while i in dic.keys():
ans.append(dic[i])
i += 1
return ans
def recurve(xianxu, zhongxu, count):
count += 1
if not zhongxu:
return
if not xianxu:
return
mid = zhongxu.index(xianxu[0])
root = treenode(xianxu[0])
del xianxu[0]
if mid == 0:
root.left = None
else:
root.left = recurve(xianxu, zhongxu[0:mid], count)
if mid == len(zhongxu)-1:
root.right = None
else:
root.right = recurve(xianxu, zhongxu[mid+1:len(zhongxu)], count)
global dic
dic[count] = root.val
return root
class treenode:
def __init__(self, val):
super().__init__()
self.val = val
self.left = None
self.right = None


京公网安备 11010502036488号