Binary Tree and programming questions ----

First, the input result and 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.

/ * * 
 * Definition for binary Tree 
 * struct the TreeNode { 
 * int Val; 
 * the TreeNode * left; 
 * the TreeNode * right; 
 * the TreeNode (int X): Val (X), left (NULL), right (NULL) {} 
 * }; 
 * / 
class Solution {
 public : 
    the TreeNode * reConstructBinaryTree (Vector < int > pre, Vector < int > VIN) {
         int vinlen = vin.size ();
         int headseq = 0 ; // root node position in preorder
         IF (vinlen == 0 ) // preorder sequence 0, 
            returnNULL;
         for ( int I = 0 ; I <vinlen; I ++ ) 
        { 
            IF (pre [ 0 ] == VIN [I])   // root node is found in the traversing position, this position from the left is a left subtree, on the right is a right subtree 
            { 
                headseq = I;
                 BREAK ; 
            } 
        } 
        
        the TreeNode * = head new new the TreeNode (pre [ 0 ]);   // first root node is a preorder traversal of
         
        Vector < int > left_pre, left_vin, right_pre , right_vin; // left subtree preorder traversal and inorder traversal, the right subtree of the preorder traversal preorder 
        
        
        for ( int= I 0 ; I <headseq; I ++ ) 
        { 
            left_pre.push_back (pre [I + . 1 ]); // preorder traversal sequence left subtree 
            left_vin.push_back (VIN [I]);    // left subtree sequence preorder 
        }
         for ( int I = headseq + . 1 ; I <vinlen; I ++ ) 
        { 
            right_pre.push_back (pre [I]);   // right subtree sequence preorder traversal 
            right_vin.push_back (VIN [I]);   / / inorder traversal sequence right subtree 
        }
         // recursive 
        head-> left =  reConstructBinaryTree (left_pre, left_vin);
        head -> right = reConstructBinaryTree(right_pre,right_vin);
        return head;
    }
};

 

Guess you like

Origin www.cnblogs.com/nandingahbbq/p/11268304.html