美文网首页
106、根据中序遍历和后序遍历重构二叉树

106、根据中序遍历和后序遍历重构二叉树

作者: 小碧小琳 | 来源:发表于2018-07-27 14:29 被阅读0次

这道题跟105题思路是一样的:

  • 1、确定递归结束条件:
    当传入函数的中序遍历结果与后序遍历结果都会空时,就返回None。

  • 2、确定每次传入递归函数的参数:
    1、一开始递归函数得到的是中序遍历list和后序遍历list,那么上述两个list就是参数。
    2、根据后序遍历确定根节点root = TreeNode(post[-1]),于是中序遍历结果中,得到root的index = in.index(post[-1])。
    3、由上,得到左子树的中序遍历结果与后序遍历结果,得到右子树的中序遍历结果与后序遍历结果。然后分别在左子树和右子树的重构函数中传入两个list即可。

代码注意事项:
1、index是list方法,应该是L.index(item)调用,其中item是需要被确定索引位置的元素。
2、root是节点类实例,需要调用类实现。
3、若是想要返回节点的值,那么只需要Node.val即可。不要在val后面加括号。

代码:

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

class Solution:
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if len(inorder) == 0 and len(postorder) == 0:
            return None
        root = TreeNode(postorder[-1])
        #在这地方出了错。。index中传入的应该是postorder[-1]而不是root
        index = inorder.index(postorder[-1])
        root.left = self.buildTree(inorder[0:index],postorder[0:index])
        root.right = self.buildTree(inorder[index+1:],postorder[index:-1])
        return root

相关文章

网友评论

      本文标题:106、根据中序遍历和后序遍历重构二叉树

      本文链接:https://www.haomeiwen.com/subject/rctgmftx.html