Recursive 32ms c++ solution


  • 0
    P
    class Solution {
        TreeNode* help(vector<int>::iterator inor,vector<int>::iterator post,int n){
            if(n==0) return NULL;
            int parent = post[n-1];
            TreeNode* root = new TreeNode(parent);
            int n_left = 0;
            while(inor[n_left]!=parent) n_left++;
            int n_right = n-n_left-1;
            root->left = help(inor,post,n_left);
            root->right = help(inor+n_left+1,post+n_left,n_right);
            return root;
        }
    public:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            return help(inorder.begin(),postorder.begin(),inorder.size());
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.