题外话
感觉嵌入式方向的实习不好找啊,心慌……
刷刷算法题看看可不可以做C++后台吧……
正文
思路为递归。具体思路下面的博文记载的十分详细。用C++只比Java少了一点的代码……
二分,分成左子树跟右子树
代码如下
class TreeNode
{
public:
static TreeNode* ConstructTree(vector<int> pre, vector<int> vin);
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* TreeNode::ConstructTree(vector<int> pre, vector<int> vin)//pre 为先序遍历序列,vin 为中序遍历序列
{
if (pre.size() > 0)//判断是否是空序列
{
vector<int>::iterator RootIndex = vin.end();
TreeNode* root = new TreeNode(pre[0]);
for (vector<int>::iterator i = vin.begin(); i < vin.end(); i++)//查找中序遍历Root节点的位置,根据该位置分出左子树与右子树节点
{
if (*i == root->val)
{
RootIndex = i; break;
}
}
vector<int> LeftTreePre, LeftTreeVin;
vector<int> RightTreePre, RightVin;
vector<int>::iterator NextPreIt = pre.end();
copy(vin.begin(), RootIndex, std::back_inserter(LeftTreeVin));//拷贝
copy(RootIndex + 1, vin.end(), std::back_inserter(RightVin));//拷贝
for (vector<int>::iterator i = pre.begin() + 1; i < pre.end(); i++)//查找前序遍历中,左子树跟右子树的分界处,查找到了NextPreIt指向该处,否则为结尾。
{
if (find(LeftTreeVin.begin(), LeftTreeVin.end(), *i) == LeftTreeVin.end())
{
NextPreIt = i;
break;
}
}
copy(pre.begin() + 1, NextPreIt, std::back_inserter(LeftTreePre));//拷贝
copy(NextPreIt, pre.end(), std::back_inserter(RightTreePre));//拷贝
root->left = ConstructTree(LeftTreePre, LeftTreeVin);//递归求左子树
root->right = ConstructTree(RightTreePre, RightVin);//递归求右子树
return root;
}
return nullptr;
}
没什么说的……