1.从前序与中序遍历序列构造二叉树
1.1 解题思路
前序序列的第一个节点为根节点。 中序序列的根节点的值在中间,并且左侧为其左子树,右侧为其右子树。
重建算法思路很清晰,先确定根节点,然后从中序序列中找到根节点的左子树和右子树;随后递归重建其左子树和右子树即可。
1)在中序序列中寻找根节点的编号,根据编号是否位于序列两端判断是否存在左右子树,并重建。
2)根据两个序列,重建某棵二叉树
1.2 code
//
// Created by wbzhang on 2020/6/29.
//
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* constructTree(vector<int> preorder,vector<int> inorder){
if(preorder.size()*inorder.size()==0){
return NULL;
}
// 1.根节点的值
int rootValue = preorder[0];
TreeNode* root = new TreeNode(rootValue);
root->left = root->right = NULL;
// 2.从中序遍历序列中寻找根节点的值
int inRootInd = 0;
for(int i=0;i<inorder.size();++i){
if(inorder[i]==rootValue){
inRootInd = i;
}
}
// 然后分别根据某一段来重建左子树和右子树,再将其连接到根节点即可
// int leftLength = inRootInd;
if(inRootInd!=0){
vector<int> leftPreVec(preorder.begin()+1,preorder.begin()+inRootInd+1);
vector<int> leftInVec(inorder.begin(),inorder.begin()+inRootInd);
root->left = constructTree(leftPreVec,leftInVec);
}else root->left = NULL;
if(inRootInd != inorder.size()-1){
vector<int> rightPreVec(preorder.begin()+inRootInd+1,preorder.end());
vector<int> rightInVec(inorder.begin()+inRootInd+1,inorder.end());
root->right = constructTree(rightPreVec,rightInVec);
}else root->right = NULL;
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()*inorder.size()==0 ) return NULL;
return constructTree(preorder,inorder);
}
int main(){
vector<int> preorder={3,9,20,15,7};
vector<int> inorder={9,3,15,20,7};
TreeNode* root = buildTree(preorder,inorder);
return 0;
}
扩展:从中序和后续遍历序列重建二叉树
中序序列的特点与上面描述相同。 后序遍历序列的特点在于根节点在序列最后面,则重建思路与之相同。