篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了105. Construct Binary Tree from Preorder and Inorder Traversal相关的知识,希望对你有一定的参考价值。
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.
解析
// Construct Binary Tree from Preorder and Inorder Traversal
class Solution_105 {
public:
//运行时间:9ms
//占用内存:640k
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size()==0||inorder.size()==0||preorder.size()!=inorder.size())
{
return NULL;
}
TreeNode* root = new TreeNode(preorder[0]);
if (preorder.size() == inorder.size() && inorder.size() == 1)
{
return root;
}
//auto pos = inorder.size() > 1 ? find(inorder.begin(), inorder.end(), preorder[0]) : inorder.begin();
auto pos = find(inorder.begin(), inorder.end(), preorder[0]) ;
//preorder用下标分开也可以
vector<int> inorder1(inorder.begin(), pos); //pos指向容器最后一个元素的下一个位置
vector<int> inorder2(pos + 1, inorder.end());
vector<int> preorder1(preorder.begin() + 1, preorder.begin() + 1 + inorder1.size()); //cnt=inorder1.size()
vector<int> preorder2(preorder.begin() + 1 + inorder1.size(), preorder.end());
//auto iter = preorder.begin();
//int cnt = 0;
//while (iter != pos)
//{
// iter++;
// cnt++;
//}
////preorder用下标分开也可以
//vector<int> inorder1(inorder.begin(), pos);
//vector<int> inorder2(pos + 1, inorder.end());
//vector<int> preorder1(preorder.begin() + 1, preorder.begin() + 1 + cnt); //cnt=inorder1.size() //报alloc错误
//vector<int> preorder2(preorder.begin() + 1 + cnt, preorder.end());
if (preorder1.size()>0)
{
root->left = buildTree(preorder1, inorder1);
}
if (preorder2.size()>0)
{
root->right = buildTree(preorder2, inorder2);
}
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
return build(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode *build(vector<int> &preorder, vector<int> &inorder, int l1, int r1, int l2, int r2)
{
if (l1 > r1)
return NULL;
int gen = preorder[l1];
int i, cnt = 0;
for (i = l2; i <= r2&&inorder[i] != gen; cnt++, i++); //找到当前根节点在inorder中的位置
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = gen;
root->left = build(preorder, inorder, l1 + 1, l1 + cnt, l2, i - 1); //位置信息要准确
root->right = build(preorder, inorder, l1 + 1 + cnt, r1, i + 1, r2);
return root;
}
};
题目来源
以上是关于105. Construct Binary Tree from Preorder and Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章