参考资料:
[1]见本页标准答案
思路:
重建二叉树分为重建左子树、重建右子树
自己的解答:
struct BinaryTreeNode{
int m_nKey;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode(int nVal) :m_nKey(nVal), m_pLeft(nullptr), m_pRight(nullptr)
{}
};
//重建二叉树
BinaryTreeNode* ReConstructBinaryTree(vector<int> pre,vector<int> vin)
{
if (pre.size() <= 0)
return nullptr;
BinaryTreeNode* pHead = new BinaryTreeNode(pre[0]);
//找到中序遍历的根节点
//找到左子树的前序遍历和中序遍历
//找到右子树的前序遍历和中序遍历
//重建左子树和重建右子树
//找到中序遍历的根节点
int nVinRoot = 0;
for (int i = 0; i < vin.size(); i++)
{
if (vin[i] == pre[0])
{
nVinRoot = i;
break;
}
}
vector<int> vecPreLeft, vecVinLeft;
vector<int> vecPreRight,vecVinRight;
//找到左子树的前序遍历和中序遍历
//找到右子树的前序遍历和中序遍历
for (int i = 0; i < nVinRoot; i++)
{
vecPreLeft.push_back(pre[i+1]);
vecVinLeft.push_back(vin[i]);
}
for (int j = nVinRoot+1; j < pre.size(); j++)
{
vecPreRight.push_back(pre[j]);
vecVinRight.push_back(vin[j]);
}
//重建左子树和重建右子树
pHead->m_pLeft = ReConstructBinaryTree(vecPreLeft,vecVinLeft);
pHead->m_pRight = ReConstructBinaryTree(vecPreRight,vecVinRight);
return pHead;
}
标准答案:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(vin.size()<=0)
return nullptr;
//前序遍历第一个节点为根节点
TreeNode* head = new TreeNode(pre[0]);
//找到中序遍历中根节点所在的位置
int gen;
for(int i = 0;i <vin.size();i++)
{
if(pre[0] == vin[i])
{
gen =i;
break;
}
}
//前序遍历左子树,前序遍历右子树,中序遍历左子树,中序遍历右子树
vector<int> left_pre,right_pre;
vector<int> left_vin, right_vin;
//将前序遍历左子树放入前序遍历左子树中,将中序遍历左子树放入中序遍历左子树中
for(int i =0;i<=gen-1;i++)
{
left_vin.push_back(vin[i]);
left_pre.push_back(pre[i+1]);
}
//将前序遍历右子树放入前序遍历右子树中,将中序遍历右子树放入中序遍历右子树中
for(int i =gen+1;i<vin.size();i++)
{
right_vin.push_back(vin[i]);
right_pre.push_back(pre[i]);
}
head->left = reConstructBinaryTree(left_pre,left_vin);
head->right = reConstructBinaryTree(right_pre,right_vin);
return head;
}
};