leetcode[106]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.

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

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

 * };

 */

class Solution {

public:

template<typename Iter>

void creatTree(TreeNode *&root,Iter inBeg,Iter inEnd, Iter posBeg,Iter posEnd)

{

    if(inBeg==inEnd||posBeg==posEnd)

    {

        root=NULL;

        return;

    }

    posEnd--;

    root=new TreeNode(*posEnd);

    Iter tmp=find(inBeg,inEnd,*posEnd);

    int leftsize=tmp-inBeg;

    creatTree(root->left,inBeg,tmp,posBeg,posBeg+leftsize);

    creatTree(root->right,tmp+1,inEnd,posBeg+leftsize,posEnd);

}

TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) 

{

    TreeNode *root;

    creatTree(root,inorder.begin(),inorder.end(),postorder.begin(),postorder.end());

    return root;        

}

};

 

你可能感兴趣的:(LeetCode)