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.

思路:从中序遍历和后序遍历的数组中找到唯一的二叉树。首先找到根结点,后序遍历最末位是根结点,然后找出中序遍历根结点的位置,记录index,且计算左子树的长度。递归方法,在左子树和右子树的遍历数组中再找出左子树和右子树的根结点,以此类推。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void buildBST(TreeNode *&root,vector<int> &inorder,int inBegin,int inEnd,vector<int> &postorder,int postBegin,int postEnd)
    {
        if(inBegin>inEnd || postBegin>postEnd)
            return;
        int pRoot=postorder[postEnd];
        root=new TreeNode(pRoot);
        int index=0;
        for(int i=0;i<=inEnd;i++)
        {
            if(pRoot==inorder[i])
            {
                index=i;
                break;
            }
        }
        int in_len=index-inBegin;
        buildBST(root->left,inorder,inBegin,index-1,postorder,postBegin,postBegin+in_len-1);
        buildBST(root->right,inorder,index+1,inEnd,postorder,postBegin+in_len,postEnd-1);
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        TreeNode *root;
        if(inorder.empty() || postorder.empty())
            return NULL;
        int inEnd=inorder.size()-1;
        int postEnd=postorder.size()-1;
        buildBST(root,inorder,0,inEnd,postorder,0,postEnd);
        return root;
    }
};

 

posted @ 2014-04-26 19:25  Awy  阅读(141)  评论(0编辑  收藏  举报