And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free.
For example, given
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
Returns the following binary tree:
3
/ \
9 20
/ \
15 7
limit:
0 <= the number of nodes <= 5000
Problem-solving ideas
- According to a first element to establish root preamble sequence;
- The sequence element found in the sequence, the determined left and right subtrees of the root node in order of the sequence;
- Determining left and right subtree preamble sequence motif sequence in the preceding;
- Establishing left subtree preamble sequence by a left subtree and motif sequence;
- Establishing the right subtree of the preamble sequence and the right subtree of the motif sequences.
def buildTree(preorder, inorder):
if not preorder:
return None
loc = inorder.index(preorder[0])
root = TreeNode(preorder[0])
root.left = buildTree(preorder[1: loc + 1], inorder[: loc])
root.right = buildTree(preorder[loc + 1:], inorder[loc + 1:])
return root