题目
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
解题思路
跟LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal一模一样的解法,只是把前序数组的每次输出第一个换成后序数组输出最后一个。此外,105是先左节点再右节点,106反过来。
# 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: List[int], postorder: List[int]) -> TreeNode:
# while postorder:
# print(postorder.pop())
if inorder:
root_val = postorder.pop()
# print(inorder.index(root_val))
ind = inorder.index(root_val)
root = TreeNode(root_val)
root.right = self.buildTree(inorder[ind+1:], postorder)
root.left = self.buildTree(inorder[0:ind], postorder)
return root