题解 | #输出二叉树的右视图#
输出二叉树的右视图
http://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
#该方案不必老实巴交还原二叉链表 # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 求二叉树的右视图 # @param xianxu int整型一维数组 先序遍历 # @param zhongxu int整型一维数组 中序遍历 # @return int整型一维数组 #该方案不必老实巴交还原二叉链表,直接在递归时得到结果 class Solution: def solve(self , xianxu: List[int], zhongxu: List[int]) -> List[int]: # write code here def rightView(xianxu,zhongxu,level): global res #使用全局变量 if zhongxu==[]: #zhongxu缩得快,所以以它为准#修正:其实zhongxu和xianxu子串是同步缩短的 return #这两句可以换成if not zhongxu: return if level>len(res): res.append(xianxu[0]) #不同层则追加 else: res[level-1]=(xianxu[0]) #同层则覆盖 ind=zhongxu.index(xianxu[0]) rightView(xianxu[1:ind+1],zhongxu[0:ind],level+1) #分别递归遍历左右子树的串#rightView(xianxu[1:],zhongxu[0:ind],level+1) #如果用了这句,则上面要以zhongxu为准rightView(xianxu[ind+1:],zhongxu[ind+1:],level+1) # if __name__ == '__main__': #这句不能有,有则报错,可能是环境特殊 level=1;global res;res=[] rightView(xianxu,zhongxu,level) return(res) #若不采用全局变量则res始终为空