根据一棵树的中序遍历与后序遍历构造二叉树。注意:你可以假设树中没有重复的元素。
分析:区间的开闭要统一,使用变动索引的方式就无需辅助空间了
#include "_myPrint.cpp"
#include "stack"
#include "queue"
using namespace std;
// 从中序和后序遍历构造二叉树 假定二叉树中没有重复元素
class Solution{
public:
TreeNode* inPost2Tree(vector<int>& in, vector<int>& post, int inBegin, int inEnd, int postBegin, int postEnd){
// 递归写法 遵循左闭右闭的原则 使用数组索引的写法 左右索引都可以取值
// if (postBegin == postEnd) return NULL;
int midValue = post[postEnd];
TreeNode* node = new TreeNode(midValue);
if (postBegin == postEnd) return node;
// 找到中间元素在中序数组中的位置
// 迭代写法 想象目前处于迭代的过程中,注意索引要在和过程中的局部索引相加
int midIndex;
for (midIndex = inBegin; midIndex <= inEnd; midIndex++){
if (in[midIndex] == midValue){
break;
}
}
// 获取新的四个索引位置
// 中序左
int leftinBegin = inBegin;
int leftinEnd = midIndex - 1;
// 中序右
int rightinBegin = midIndex + 1;
int rightinEnd = inEnd;
// 后序左
int leftpostBegin = postBegin;
int leftpostEnd = postBegin + midIndex - inBegin - 1;
// 后序右
int rightpostBegin = leftpostEnd + 1;
int rightpostEnd = postEnd - 1;
// // log // //
cout << "----------" << endl;
cout << "leftInorder :";
for (int i = leftinBegin; i <= leftinEnd; i++) {
cout << in[i] << " ";
}
cout << endl;
cout << "rightInorder :";
for (int i = rightinBegin; i <= rightinEnd; i++) {
cout << in[i] << " ";
}
cout << endl;
cout << "leftpostorder :";
for (int i = leftpostBegin; i <= leftpostEnd; i++) {
cout << post[i] << " ";
}
cout << endl;
cout << "rightpostorder :";
for (int i = rightpostBegin; i <= rightpostEnd; i++) {
cout << post[i] << " ";
}
cout << endl;
// // log // //
node -> left = inPost2Tree(in,post,leftinBegin,leftinEnd,leftpostBegin,leftpostEnd);
node -> right = inPost2Tree(in, post, rightinBegin,rightinEnd,rightpostBegin,rightpostEnd);
return node;
}
TreeNode* buildTree(vector<int>& in, vector<int>& post){
if (in.size() == 0 || post.size() == 0) return NULL;
// 左闭右闭
return inPost2Tree(in,post,0,in.size()-1,0,post.size()-1);
}
};
int main(){
Solution s;
vector<int> in = {1,2,3,4,5};
vector<int> post = {1,3,2,5,4};
TreeNode* root = s.buildTree(in,post);
printCollection p;
p.printTreeLevelOrder(root);
}