1. Title Description
And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.
2. Recursive problem-solving
2.1 Analysis
Preorder traversal: root → → left and right
preorder: root → → left and right
- Sequence preorder traversal by the pre = {1,2,4,7,3,5,6,8} is a known root node;
- Then in order traversal sequence in = {4,7,2,1,5,3,8,6} 1 found, they will know the location of a left subtree is the left, the right is the right location 1 subtree can be obtained and the length of the left subtree right subtree, respectively 3 and 4;
- Recursive call: The preorder the root node in the left subtree and right subtree, respectively, as a tree, left subtree and right subtree respective nodes and then to find a preorder traversal, the left subtree of the root node found.
- In the left subtree example, {4,7,2} of length 3, then the corresponding pre-order traversing the root element 3, these three elements 2 and then the left subtree is the root node sequentially recursion.
2.2 Code
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre) == 0:
return None
elif len(pre) == 1:
return TreeNode(pre[0])
else:
tree = TreeNode(pre[0])
rootindex = tin.index(pre[0])
tree.left = self.reConstructBinaryTree(pre[1:rootindex+1], tin[:rootindex])
tree.right = self.reConstructBinaryTree(pre[rootindex+1:], tin[rootindex+1:])
return tree