LeetCode #106 Construct Binary Tree from Inorder and Postorder Traversal

Problem

Given inorder and postorder traversal of a tree, construct the binary tree.

Example

1
2
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

Solution

Method: Divide and Conquer

Time Complexity:

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
# 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 not inorder:
return None
elif len(inorder) == 1:
return TreeNode(inorder[0])
else:
partition = inorder.index(postorder[-1])
root = TreeNode(postorder[-1])
root.left = self.buildTree(inorder[:partition], postorder[:partition])
root.right = self.buildTree(inorder[1 + partition:], postorder[partition: -1])

return root

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for a  binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param inorder, a list of integers
# @param postorder, a list of integers
# @return a tree node
# 12:00
def buildTree(self, inorder, postorder):
if not inorder or not postorder:
return None

root = TreeNode(postorder.pop())
inorderIndex = inorder.index(root.val)

root.right = self.buildTree(inorder[inorderIndex+1:], postorder)
root.left = self.buildTree(inorder[:inorderIndex], postorder)

return root