Easy solution in cpp to it


  • 0
    N
    class Solution {
    public:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    		return build(postorder, 0, postorder.size() - 1, inorder, 0,
    				inorder.size() - 1);
    	}
    	TreeNode* build(vector<int>& postorder, int pLeft, int pRight,
    			vector<int>& inorder, int iLeft, int iRight) {
    		if (pLeft > pRight)
    			return NULL;
    		TreeNode *root = new TreeNode(postorder[pRight]);
    		int i = iLeft;
    		for (; i <= iRight; i++) {
    			if (inorder[i] == postorder[pRight]) { //找到根节点
    				break;
    			}
    		}
    		root->right = build(postorder, pLeft + (i - iLeft) , pRight - 1,
    				inorder, i + 1, iRight);
    		root->left = build(postorder, pLeft, pLeft + (i - iLeft) - 1, inorder,
    				iLeft, i - 1);
    
    		return root;
    	}
    };

Log in to reply
 

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