leetcode[105]Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder 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 preBeg,Iter preEnd,Iter inBeg,Iter inEnd)

{

    if (preBeg==preEnd||inBeg==inEnd)

    {

        root=NULL;

        return;

    }

    root=new TreeNode(*preBeg);

    vector<int>::iterator tmp=find(inBeg,inEnd,*preBeg);

    int leftsize=tmp-inBeg;

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

    creatTree(root->right, preBeg+leftsize+1,preEnd,tmp+1,inEnd);

}

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

{

    TreeNode *root;

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

    return root;

}

/*

TreeNode * creatTree(vector<int>::iterator preBeg,vector<int>::iterator preEnd,vector<int>::iterator inBeg,vector<int>::iterator inEnd)

{

    if (preBeg==preEnd||inBeg==inEnd)

    {

        return NULL;

    }

    TreeNode *root=new TreeNode(*preBeg);

    vector<int>::iterator tmp=find(inBeg,inEnd,*preBeg);

    int leftsize=tmp-inBeg;

    root->left=creatTree(preBeg+1,preBeg+leftsize+1,inBeg,tmp);

    root->right=creatTree(preBeg+leftsize+1,preEnd,tmp+1,inEnd);

    return root;

}

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

{

    return creatTree(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());

}

*/

};

 

你可能感兴趣的:(LeetCode)