重建二叉树---------根据中序加后序遍历重建二叉树
构造该二叉树的过程如下:
1. 根据后序序列的最后一个元素建立根结点;
2. 在中序序列中找到该元素,确定根结点的左右子树的中序序列;
3. 在后序序列中确定左右子树的后序序列;
4. 由左子树的后序序列和中序序列建立左子树;
5. 由右子树的后序序列和中序序列建立右子树。
下面是我在牛客网oj环境下编译测试通过的代码:
/**
* 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 *buildTree(vector<int> &inorder, vector<int> &postorder) {
/* 构造该二叉树的过程如下:
1. 根据后序序列的最后一个元素建立根结点;
2. 在中序序列中找到该元素,确定根结点的左右子树的中序序列;
3. 在后序序列中确定左右子树的后序序列;
4. 由左子树的后序序列和中序序列建立左子树;
5. 由右子树的后序序列和中序序列建立右子树。*/
if(inorder.empty()||postorder.empty()){//判断前后序是否是空的
return NULL;
}
int rootValue=postorder[postorder.size()-1];//找到后序最后一个节点,为根节点
int leftlen=0;
int rightlen=0;
TreeNode* root=new TreeNode(rootValue);
for(int i=0;i<inorder.size();i++){
if(inorder[i]==rootValue){//找到中序中的根节点,然后分为左边和右边
leftlen=i;//左子树
rightlen=inorder.size()-i-1;//右子树
break;
}
}
vector<int>leftIn(inorder.begin(),inorder.begin()+leftlen);//左子树的中序
vector<int>rightIn(inorder.begin()+leftlen+1,inorder.begin()+leftlen+1+rightlen);//右子树的中序
vector<int>leftPost(postorder.begin(),postorder.begin()+leftlen);//左子树的后序
vector<int>rightPost(postorder.begin()+leftlen,postorder.begin()+leftlen+rightlen);//右子树的后序
root->left=buildTree(leftIn,leftPost);// 由左子树的后序序列和中序序列建立左子树;
root->right=buildTree(rightIn,rightPost);// 由右子树的后序序列和中序序列建立右子树
return root;
}
};