Leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013596119/article/details/81983943

Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.

Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]

Note:

  • 1 <= pre.length == post.length <= 30
  • pre[] and post[] are both permutations of 1, 2, ..., pre.length.
  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

Answer:

Binary tree:

Depth First Traversals:
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1

recursive, pre[0](即是post[-1])作为当前tree的root node,

扫描二维码关注公众号,回复: 2968929 查看本文章

pre[1]位置的数值为left node,post[-2]的数值为right node

把pre和post按照左右分割,递归运算

特殊情况,当left node数值与right node相同时,只递归当前node的left tree(左右皆可)

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

class Solution(object):
    def buildTree(self,pre,post):
        if(len(pre)==0):
            return None
        tn=TreeNode(pre[0])
        if (len(pre)==1):
            return tn
        
        leftc=pre[1]
        rightc=post[-2]
        
        if leftc==rightc:
            tn.left=self.buildTree(pre[1:],post[0:-1])
            return tn
        
        left_tree_pre=pre[1:pre.index(rightc)]
        right_tree_pre=pre[pre.index(rightc):]
        left_tree_post=post[0:post.index(leftc)+1]
        right_tree_post=post[post.index(leftc)+1:-1]
        
        tn.left=self.buildTree(left_tree_pre,left_tree_post)
        tn.right=self.buildTree(right_tree_pre,right_tree_post)
        return tn
    def constructFromPrePost(self, pre, post):
        """
        :type pre: List[int]
        :type post: List[int]
        :rtype: TreeNode
        """
        return self.buildTree(pre,post)

猜你喜欢

转载自blog.csdn.net/u013596119/article/details/81983943