题解 | #输出二叉树的右视图#

输出二叉树的右视图

http://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0

正常思路是先复原二叉树,再宽度搜索打印,这里提供一个在复原过程中就记录的方案,比较小巧:
dic 存放每个深度的当前遍历到的最后一个值

dic={}
def ssolve(xianxu,zhongxu,n):
    index=zhongxu.index(xianxu[0])
    dic[n]=xianxu[0]
    if index>0:
        ssolve(xianxu[1:index+1], zhongxu[:index],n+1)
    if len(xianxu)-index>1:
        ssolve(xianxu[index+1:], zhongxu[index+1:],n+1)
class Solution:
    def solve(self , xianxu , zhongxu ):
        # write code here
        ssolve(xianxu, zhongxu, 0)
        return list(dic.values())
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务