//非递归前序遍历
typedef struct btnode{
char data;
struct btnode *lchild;
struct btnode *rchild;
}btnode;
typedef struct seqstack{
btnode *stack_p[SIZE]; //store pointers of stack
int tag[SIZE]; //为了非递归后续遍历使用
int top; //top of stack
}seqstack;
void push(seqstack *s,btnode *t){
if(s->top == SIZE){
printf("the stack is full\n");
}
else{
(s->top)++;
s->stack_p[s->top] = t;
}
}
btnode* pop(seqstack *s){
if(s->top==-1){
return NULL;
}
else{
(s->top)--;
return s->stack_p[(s->top)+1];
}
}
void preorder1(btnode *t){
seqstack s;
s.top = -1;
if(!t){
cout << "the tree is empty" <<endl;
}
else
{
while((s.top != -1) || (t) ){
while(t){ //栈不为空这入栈并打印,直到叶子节点
printf("%c\n",t->data);
push(&s,t);
t = t->lchild;
}
t = pop(&s); //回溯到上一个根节点
t = t->rchild;
}
}
}
二叉树重构
主要是通过前序遍历和中序遍历的特点,前序首先读取根节点,然后再中序中找到根节点的位置,将根的左右子树分开求解。递归。
因为两种遍历顺序,每种在根旁边有左右子树。故用4个vector存储4个subtree。遍历结束标志是到叶子节点,此时其分支数目为0。
btnode *reConstructBintree(vector<int> pre,vector<int> vin){
//the length of pre
int length = pre.size();
cout << length <<endl;
if(length == 0)
return NULL;
// return new btnode(pre[0]);
//define 4 vector to store left subtree and right subtree
vector<int> l_pre,r_pre,l_vin,r_vin;
btnode *head = new btnode(pre[0]);
int gen=0;
for(int i = 0; i < length; i++){
if(pre[0] == vin[i]){
gen = i;
break;
}
}
for(int i = 0; i < gen; i++){
l_pre.push_back(pre[i+1]);
l_vin.push_back(vin[i]);
}
for(int i=gen+1; i<length; i++){
r_pre.push_back(pre[i]);
r_vin.push_back(vin[i]);
}
head->lchild = reConstructBintree(l_pre,l_vin);
head->rchild = reConstructBintree(r_pre,r_vin);
return head;
}