二叉树非递归遍历,重构

来源:互联网 发布:关于朱成分分析的数据 编辑:程序博客网 时间:2024/05/23 14:54
//非递归前序遍历
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 preint 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 subtreevector<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
原创粉丝点击