【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal

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

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

 

根据定义,后序遍历postorder的最后一个元素为根。

由于元素不重复,通过根可以讲中序遍历inorder划分为左子树和右子树。

递归下去即可求解。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        return Helper(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
    TreeNode* Helper(vector<int>& inorder, int begin1, int end1, vector<int>& postorder, int begin2, int end2)
    {
        if(begin1 > end1)
            return NULL;
        else if(begin1 == end1)
            return new TreeNode(inorder[begin1]);
        
        TreeNode* root = new TreeNode(postorder[end2]);
        int i = begin1;
        for(; i <= end1; i ++)
        {
            if(inorder[i] == postorder[end2])
                break;
        }
        int leftlen = i-begin1;
        
        root->left = Helper(inorder, begin1, begin1+leftlen-1, postorder, begin2, begin2+leftlen-1);
        root->right = Helper(inorder, begin1+leftlen+1, end1, postorder, begin2+leftlen, end2-1);
        return root;
    }
};

posted @ 2014-11-30 13:46  陆草纯  阅读(409)  评论(0编辑  收藏  举报