Construct Binary Tree from Inorder and Postorder Traversal

Q:

 

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

A:

没啥好说的,细心是王道

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (inorder.empty() || postorder.empty()) return NULL;
        return buildTreeInternal(inorder, 0, inorder.size() - 1,
                                 postorder, postorder.size() - 1);
    }
    
    TreeNode *buildTreeInternal(vector<int> &inorder, int start, int end,
                        vector<int> &postorder, int root_pos_post) {
        if (start > end) return NULL;
        if (root_pos_post < 0 || root_pos_post >= postorder.size()) return NULL;
        int root_pos_in = -1;
        for (int i = start; i <= end; ++i) {
            if (inorder[i] == postorder[root_pos_post]) {
                root_pos_in = i;
                break;
            }
        }
        if (-1 == root_pos_in) {
            assert(0);
            return NULL;
        }
        TreeNode* root = new TreeNode(postorder[root_pos_post]);
        if (end >= root_pos_in + 1) {
            root->right = buildTreeInternal(inorder, root_pos_in + 1, end,
                                            postorder, root_pos_post - 1);
            root_pos_post -= end - root_pos_in;
        }
        if (start <= root_pos_in - 1) {
            root->left = buildTreeInternal(inorder, start, root_pos_in - 1,
                                           postorder, root_pos_post - 1);
        }
        return root;
    }
};

 

posted @ 2013-07-07 01:07  dmthinker  阅读(128)  评论(0)    收藏  举报