LeetCode_Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder 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> &inorder, int inStart, int inEnd, vector<int> &postorder, int postStart, int postEnd)

    {

        int temp = postorder[postEnd] ;

        TreeNode * root = new TreeNode(temp) ;

    

        if(inStart == inEnd ) return root;

    

        int i ;

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

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

      

        root->left = inStart <= i-1 ? constructSubtree(inorder, inStart, i-1, postorder,postStart, postStart + i - inStart - 1  ) : NULL;

    

        root->right = i+1 <= inEnd ? constructSubtree(inorder, i+1, inEnd, postorder, postStart + i - inStart, postEnd -1 ) : NULL ;

 

        return root ;

 

    }

 

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

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

        // DO NOT write int main() function

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

        int temp = postorder[postorder.size()-1] ;

        TreeNode * root = new TreeNode(temp) ;

        

        int i;

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

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

         

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

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

        

        return root ;

    }

};

 

你可能感兴趣的:(LeetCode)