卖萌的弱渣

I am stupid, I am hungry.

Construct BTree From Preorder and Inorder Traversal

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

Note: You may assume that duplicates do not exist in the tree.

Solution

(Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py) download
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
# 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, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """

        n = len(preorder)
        if n == 0:
            return None

        root = TreeNode(preorder[0])
        indexIn = inorder.index(preorder[0])
        leftL = indexIn
        root.left = self.buildTree(preorder[1:(1+leftL)], inorder[0:indexIn])
        root.right = self.buildTree(preorder[1+leftL:], inorder[indexIn+1,:])

        return root