[leetcode刷题系列]Construct Binary Tree from Inorder and Postorder Traversal

这种题还真是没怎么写过,acm中基本上见不到这类提。不过简单想一下很容易能想到算法。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    TreeNode * dfs(int in_left, int in_right, vector<int> & inorder,
            int post_left, int post_right, vector<int> & postorder){
                if(in_left > in_right)
                    return 0;
                TreeNode * ret = new TreeNode(postorder[post_right]);
                for(int i = in_left; i <= in_right; ++ i)
                    if(inorder[i] == postorder[post_right]){
                        ret->left = dfs(in_left, i - 1, inorder, post_left, post_left + i - 1 - in_left, postorder);
                        ret->right = dfs(i + 1, in_right, inorder, post_right - 1 - (in_right - i - 1),post_right - 1, postorder); 
                        return ret;
                    }
                return 0;
            }
public:
    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 0;
        return dfs(0, inorder.size() - 1, inorder, 0, postorder.size() - 1, postorder);
    }
};


你可能感兴趣的:([leetcode刷题系列]Construct Binary Tree from Inorder and Postorder Traversal)