[leetcode]Construct Binary Tree from Inorder and Postorder Traversal

 

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

class Solution {
public:
    TreeNode *buildTree(vector<int> &in, int inStart, vector<int> &post, int postStart, int len){
        if (inStart<0 || inStart+len>in.size() || postStart<0 || postStart+len>post.size() || len<1)
            return NULL;

        TreeNode *root = new TreeNode(post[postStart+len-1]);//注意这里是postStart+len-1而不是post.size()-1
        int i = 0;
        for (i = 0; i < len; i++)
            if (in[inStart + i] == root->val)
                break;

        int leftLen = i;
        int rightLen = len - 1 - leftLen;

        root->left = buildTree(in, inStart, post, postStart, leftLen);
        root->right = buildTree(in, inStart+leftLen+1, post, postStart+leftLen, rightLen);

        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() != postorder.size() || inorder.size()<1)
            return NULL;

        return buildTree(inorder, 0, postorder, 0, inorder.size());
    }
};

 

 

 

 

 

EOF

你可能感兴趣的:(LeetCode)