二叉树非递归遍历,重构

//非递归前序遍历
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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值