To prove safety offer- reconstruction of a binary tree - the tree -python

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: first find out before traversing the first to root. Then look for the value of the position in order traversal is set to index 
Using a recursive: a preorder traversal of the left subtree length than the root to (1: index + 1) while preorder left subtree length (: index)
                  Preorder traversal of the right subtree in length in addition to the root node (index + 1 :) preorder while the right subtree of length (index + 1 :) root is because Index
 
# - * - Coding: UTF-. 8 - * - 
# class the TreeNode: 
#      DEF the __init __ (Self, X): 
#          self.val = X 
#          self.left = None 
#          self.right = None 
class Solution:
     # return configuration TreeNode root 
    DEF reConstructBinaryTree (Self, pre, tin):
         # the Write code here Wallpaper 
        # pre-order traversal is a former tin is preorder 
        IF  not pre or  not tin:
             return None
        root = TreeNode(pre[0])
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre[1:index+1],tin[:index])
        root.right = self.reConstructBinaryTree(pre[index+1:],tin[index+1:])
        return root

Guess you like

Origin www.cnblogs.com/ansang/p/11892350.html