Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Subscribe to see which companies asked this question
递归就可以了。
#include<algorithm>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()==||inorder.size()==||find(inorder.begin(),inorder.end(),preorder[])==inorder.end())
return NULL;
auto rootindex=find(inorder.begin(),inorder.end(),preorder[]);
TreeNode *root = new TreeNode(preorder[]);
vector<int> subleft,subright;
preorder.erase(preorder.begin());
if(rootindex!=inorder.begin())
subleft.insert(subleft.begin(),inorder.begin(),rootindex);
if(rootindex!=inorder.end()-)
subright.insert(subright.begin(),rootindex+,inorder.end());
root->left=buildTree(preorder,subleft);
root->right=buildTree(preorder,subright);
return root;
}
};