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.
Ideas:
Found inside the pre-order traversing the first number, this number is the root, and then find the number in traversing the array, the number in front of the number that constitutes a left subtree of the root, which points to the right of the right sub-configuration tree.
Then recursion
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])
target = pre[0]
for i in range(0,len(tin)):
if tin[i] == target:
root = TreeNode(target)
root.left = self.reConstructBinaryTree(pre[1:i+1],tin[:i])
root.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:])
return root
I do not know not to brush hard, the feeling of title to prove safety offer no hard leetcode