题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

简易递归实现二叉树重建(先、中)

func reConstructBinaryTree( pre []int ,  vin []int ) *TreeNode {
    // write code here
    // 利用先序确定根节点位置, 再通过中序节点找到根节点, 确定左子树、右子树节点长度, 进行分治 还原节点
    
    if len(pre) == 0 { return nil }
    r, idx := pre[0], 0
    
  	// 找到
    for _, v := range vin {
        if v == r {
            break
        } 
        idx++
    }
    
    return &TreeNode{
        r, 
        // 左子树
        reConstructBinaryTree(pre[1:idx + 1], vin[:idx]), 
        // 右子树
        reConstructBinaryTree(pre[idx+1:], vin[idx+1:]), 
    }
}
全部评论

相关推荐

三题看不懂四题不明白二题无法AC T=int(input()) for _ in range(T): n=int(input()) s=input().split() k,mx=1,1 for i in range(len(s)-1): if len(s[i])<len(s[i+1]): k+=1 elif len(s[i])==len(s[i+1]): if s[i]<=s[i+1]: k+=1 ...
恭喜臭臭猴子:第二题用栈就行。合法的括号直接出栈了,剩下的是不合法的,肯定都得一个一个走。出入栈的过程中得记下进栈的括号的下标。最后栈里剩下的括号如果相邻两个的下标不连续,说明它们中间有一个合法的括号序列被出栈,结果加一
投递拼多多集团-PDD等公司10个岗位 > 拼多多求职进展汇总 笔试
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务