[Tree]106. Construct Binary Tree from Inorder and Postorder Traversal

字数 140阅读 5
  • 分类:Tree
  • 时间复杂度: O(n) 这种把树的节点都遍历一遍的情况时间复杂度为O(n)
  • 空间复杂度: O(h) 树的节点的深度

106. Construct Binary Tree from Inorder and Postorder Traversal

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

代码:

# 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':
        
        if inorder==None or postorder==None or len(inorder)!=len(postorder):
            return None
        
        return self.helper(inorder,postorder,0,len(inorder)-1,0,len(postorder)-1)
    
    def helper(self,inorder,postorder,in_st,in_ed,po_st,po_ed):
        #设置出口
        if po_st>po_ed or in_st>in_ed:
            return
        root=TreeNode(postorder[po_ed])
        for i in range(in_st,in_ed+1):
            if inorder[i]==postorder[po_ed]:
                break
        root.left=self.helper(inorder,postorder,in_st,i-1,po_st,po_st+(i-in_st)-1)
        root.right=self.helper(inorder,postorder,i+1,in_ed,po_st+(i-in_st),po_ed-1)
        return root

讨论:

1.105题的一道followup,考察中序遍历和后序遍历的特点,利用递归/分治来解这道题
2.注意4个位置

推荐阅读更多精彩内容