根据前序遍历和中序遍历树构造二叉树
思路:(https://blog.csdn.net/mmwwxx123/article/details/81510702)该链接中已经提到。直接上代码:
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
int len = vin.size();
if(len == 0){
return NULL;
}
vector<int> left_pre, right_pre;
vector<int> left_in, right_in;
TreeNode *root = new TreeNode(pre[0]);
int index =-1;
for(int i=0; i<len; i++){
if(vin[i] == pre[0]){
index = i;
break;
}
}
for(int i=0; i<index; i++){
left_pre.push_back(pre[i+1]);
left_in.push_back(vin[i]);
}
for(int i=index+1; i<len; i++){
right_pre.push_back(pre[i]);
right_in.push_back(vin[i]);
}
root->left = reConstructBinaryTree(left_pre, left_in);
root->right = reConstructBinaryTree(right_pre, right_in);
return root;
}
};
根据中序遍历和后序遍历树构造二叉树
解题思路
思路和用前序遍历和后序遍历树构造二叉树类似
1、首先根据后序遍历序列的最后一个数字创建根结点(后序遍历序列的最后一个数字就是根结点)
2、然后在中序遍历序列中找到根结点所在的位置,这样就能确定左、右子树结点的数量,这样也就分别找到了左、右子树的中序遍历序列和后序遍历序列。
3、然后用递归的方法去构建左、右子树,直到叶子结点。
根据中序加后序遍历重建二叉树
代码如下:
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if(inorder.size()==0||postorder.size()==0)
return NULL;
if(inorder.size()!=postorder.size())
return NULL;
int root_index=-1;
vector<int> inL,inR,postL,postR;
int len=postorder.size();
TreeNode *root=new TreeNode(postorder[len-1]);
for(int i=0;i<len;i++)
{
if(postorder[len-1]==inorder[i])
{
root_index=i;
break;
}
}
for(int j=0;j<root_index;j++)
{
postL.push_back(postorder[j]);
inL.push_back(inorder[j]);
}
int k=root_index+1;
for(;k<inorder.size();k++)
{
postR.push_back(postorder[k-1]);
inR.push_back(inorder[k]);
}
root->left=buildTree(inL,postL);
root->right=buildTree(inR,postR);
return root;
}
};