基本思路是递归,参数是 i, j 是 绝对坐标,想对于 整体的坐标
参考自:
https://www.cnblogs.com/bmrs/archive/2010/08/19/SloveTree.html
#include<iostream>
#include<vector>
#include<string>
using namespace std;
string pre = "ABDHLEKCFG";
string mid = "HLDBEKAFCG";
string post = "LHDKEBFGCA";
struct node{
char val;
struct node *left;
struct node *right;
};
void PreMTree(node* &r,int i,int j,int len);
void PostMTree(node* &r,int i,int ,int len);
void PrePrint(node* r);
void PostPrint(node* r);
int main()
{
struct node *r1 = NULL;
struct node *r2 = NULL;
int len = pre.size();
//cout<<"len: "<<len<<endl;
PreMTree(r1,0,0,len);
PrePrint( r1);
cout<<endl;
PostMTree(r2,len-1,0,len);
PostPrint(r2);
cout<<endl;
return 0;
}
void PreMTree(node* &r,int i,int j,int len)
{
if (len<=0)
{
return;
}
r = new node;
r->left = NULL;
r->right = NULL;
r->val = pre[i];
// cout<<"r->val: "<<r->val<<" ";
int flag;
for (int k=0;k<mid.size();k++)
{
if (mid[k]==pre[i])
{
flag = k;
break;
}
}
PreMTree(r->left,i+1,j,flag-j);
PreMTree(r->right,i+(flag-j)+1,flag+1,len-(flag-j)-1);
}
void PostMTree(node* &r,int i,int j ,int len)
{
if (len<=0)
{
// cout<<"dfd"<<endl;
return;
}
r = new node;
r->val = post[i];
r->left = NULL;
r->right = NULL;
int flag;
for (int k=0;k<mid.size();k++)
{
if (mid[k]==post[i])
{
flag = k;
break;
}
}
PostMTree(r->left,i-(len-(flag-j)-1)-1,j,flag-j);
PostMTree(r->right,i-1,flag+1,len-(flag-j)-1);
}
void PrePrint(node* r){
if (r)
{
cout<<r->val<<" ";
PrePrint(r->left);
PrePrint(r->right);
}
}
void PostPrint(node* r){
if (r)
{
PostPrint(r->left);
PostPrint(r->right);
cout<<r->val<<" ";
}
}
后记:
我感觉这中题目还是不能多想,最好还是备注吧。
- 要注意递归终止的条件:(1),如果左右坐标一样,那就只剩一个了,返回该根;(2)左右元素长度均大于0;
- 注意在递归的时候,其实不复杂,函数变量包括:原始的两个数组,pL,pr, vL, vr。
- 其中,pL ,pr的更新稍复杂一点,vL ,vr的更新及其简单;pL在Left树中的更新也仅仅+1即可。
剑指offer上的原题:
/**
* 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) {
int p = pre.size();
int v = vin.size();
if (p!=v || p==0)return NULL;
else return BT(pre,vin,0,p-1,0,v-1);
}
TreeNode* BT(vector<int>pre,vector<int>vin,int pl,int pr,int vl,int vr)
{
//if (vl<0 || vr >=vin.size() || pr>=pre.size() || pl<0)return NULL;
int tmp = pre[pl];
TreeNode* root = new TreeNode(tmp);
if (pl==pr)return root;
int k = vl;
for (;k<=vr;k++)
{
if (vin[k]==tmp)break;
}
int len_left = k-vl;
int len_right = vr-k;
if (len_left>0)root->left = BT(pre,vin,pl+1,pl+len_left,vl,k-1);
if (len_right>0)root->right = BT(pre,vin,pl+len_left+1,pr,k+1,vr);
return root;
}
};