A simple cpp recursive solution.


  • 1
    S
    class Solution {
    public:
    int index = 0;
    int find(int l, int h, vector<int>& inorder,int s) {
    	for (auto i = l; i <= h; i++) {
    		if (inorder[i] == s)
    			return i;
    	}
    	return -1;
    }
    TreeNode* construct(vector<int>& postorder, vector<int>& inorder,int l,int h) {
    	if (l>h)
    		return NULL;
    	TreeNode* root = new TreeNode(postorder[index++]);
    	int pos = find(l, h, inorder, root->val);
    	root->right = construct(postorder, inorder,pos+1,h);
    	root->left = construct(postorder, inorder,l,pos-1);
    	return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    	TreeNode* root = NULL;
    	reverse(postorder.begin(),postorder.end());
    	return construct(postorder, inorder,0,inorder.size()-1);
    }
    

    };


  • 0
    C
    This post is deleted!

Log in to reply
 

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