leetcode 889

此题是个好题目。让我想起了当年学数据结构和编译原理时候的前序,后序,中序表达式。该题的思路也比较清楚,首先我想到的是前序第一个数字肯定是根节点,根节点后面跟着的肯定是左子树的值,接着我们在后序里面找到这个左子树的值,该值之前的所有数肯定都属于这个子树。就这样可以将原问题化为更小的子问题。在实现上述思路的时候,又想到对于每个数字,在前序列表中,该数字后面的肯定是它的左子树,在后序列表中该数字前面的肯定是它的右子树。这个思路实现起来坑太多,估计是我的结构设置的不好,导致特殊情况太多,看了一下discuss中,有人是这样做的,这里把代码贴出来(果然discuss中都是人才)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def constructFromPrePost(self, pre, post):
        """
        :type pre: List[int]
        :type post: List[int]
        :rtype: TreeNode
        """
        if len(pre) == 0:
            return None
        root = TreeNode(pre[0])
        if len(pre) == 1:
            return root
        left = pre[1]
        temp_post = post.copy()
        left_index = temp_post.index(left)
        left_post = post[0:left_index+1]
        left_pre = pre[1:left_index+2]
        pos = 2 + left_index
        
        if pos > len(pre) - 1:
            right_pre = []
            right_post = []
        else:
            right_pre = pre[pos:]
            right_post = post[left_index+1:-1]
        
        left_node = self.constructFromPrePost(left_pre,left_post)
        right_node = self.constructFromPrePost(right_pre,right_post)
        root.left = left_node
        root.right = right_node
        return root

 

别人的代码:

    def constructFromPrePost(self, pre, post):
        stack = [TreeNode(pre[0])]
        j = 0
        for v in pre[1:]:
            node = TreeNode(v)
            while stack[-1].val == post[j]:
                stack.pop()
                j += 1
            if not stack[-1].left:
                stack[-1].left = node
            else:
                stack[-1].right = node
            stack.append(node)
        return stack[0]

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值