LeetCode_Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.



Note:

You may assume that duplicates do not exist in the tree.

  

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

  TreeNode * constructSubtree(vector<int> &preOrder, int preStart, int preEnd, vector<int> &inOrder, int inStart, int inEnd){

      

    // if(preStart < preEnd) return NULL ;

       

     int temp = preOrder[preStart] ;

     TreeNode *root = new TreeNode(temp) ;

     if(preStart == preEnd)

        return root ;

        

     int i;

     for(i = inStart ; i<= inEnd ;i++)

       if(inOrder[i] == temp ) break;

      

     root->left = preStart+1 <= preStart+i-inStart ? constructSubtree(preOrder, preStart+1, preStart+i-inStart, inOrder, inStart, i-1) : NULL;

     root->right = preStart+i-inStart+1 <=  preEnd ? constructSubtree(preOrder, preStart+i-inStart+1,  preEnd, inOrder, i+1, inEnd) : NULL;

     

     return root ;

 } 

    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

    

        if(preorder.size() == 0 ) return NULL;

        TreeNode *root = new TreeNode(preorder[0]) ;

        if(preorder.size() == 1 ) return root ;

        

        int i;

        int temp = preorder[0] ;

        

        for(i = 0; i< inorder.size(); i++)

           if(inorder[i] == temp) break ;

        

         root->left = 1 <= i ? constructSubtree(preorder, 1,i,inorder, 0, i-1) : NULL  ;

    

         root->right = i+1 <= preorder.size()-1 ? constructSubtree(preorder, i+1,preorder.size()-1, inorder, i+1, inorder.size() -1): NULL ;

        

        return root;

   }

   

};

 

你可能感兴趣的:(LeetCode)