LeetCode #889 Construct Binary Tree from Preorder and Postorder Traversal

Problem

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
2
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.

Solution

Method: Divide and Conquer

Time Complexity: O(n)

Space Complexity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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 not pre and not post:
return None
elif len(pre) == 1:
return TreeNode(pre[0])
elif len(pre) == 2:
ret = TreeNode(pre[0])
ret.left = TreeNode(pre[1])
return ret
else:
root = TreeNode(pre[0])
partition = post.index(pre[1]) + 1

root.left = self.constructFromPrePost(pre[1: 1 + partition], post[:partition])
root.right = self.constructFromPrePost(pre[1 + partition:], post[partition: - 1])

return root