[Offer] 10- rebuild binary tree to prove safety

topic:

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.


 

Thinking:

Before traversing Binary Tree, the first number is the root node, the root node to find the location in order traversal, can distinguish the left and right subtrees. And again at the left and right subtree, respectively, to find the root node in a preorder traversal, the operation described above is repeated. ---> recursive! !

# -*- coding:utf-8 -*-
# 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 not pre or not tin:
            return None
        if len(pre) <= 0 or len(tin) <= 0:
            return None
        root The TreeNode = (pre [0])   # previous traversal order to find the root, after finding treenode into the 
        POS = tin.index (pre [0])   # root node is found in preorder position 

        tinLeft = TiN [: POS]   # left subtree inorder traversal 
        tinRight = TiN [POS +. 1 :] 

        preLeft = pre [. 1: POS +. 1]   # left subtree preorder traversal of 
        preRight = pre [POS +. 1 :] 

        # again re branching off the left subtree, and a preamble inorder traversal, as new traversal recursion 
        root.left = self.reConstructBinaryTree (preLeft, tinLeft) 
        root.right = self.reConstructBinaryTree (preRight, tinRight)
         return the root

 Problems encountered when writing:

1. Consider the special case where: No preamble / inorder traversal of the case; preamble / length in order for the case where 0

2. pre [0] is the root node, but put it into a binary tree TreeNode in! TreeNode in the left subtree is left, right is right subtree

3. root class TreeNode since it is now, there will be a left and right

Guess you like

Origin www.cnblogs.com/RebeccaG/p/11966461.html