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()==0||inorder.size()==0||find(inorder.begin(),inorder.end(),preorder[0])==inorder.end())
return NULL;
auto rootindex=find(inorder.begin(),inorder.end(),preorder[0]);
TreeNode *root = new TreeNode(preorder[0]);
vector<int> subleft,subright;
preorder.erase(preorder.begin());
if(rootindex!=inorder.begin())
subleft.insert(subleft.begin(),inorder.begin(),rootindex);
if(rootindex!=inorder.end()-1)
subright.insert(subright.begin(),rootindex+1,inorder.end());
root->left=buildTree(preorder,subleft);
root->right=buildTree(preorder,subright);
return root;
}
};
【leetocde】 105. Construct Binary Tree from Preorder and Inorder Traversal
原文:http://www.cnblogs.com/LUO77/p/5616963.html