zoukankan      html  css  js  c++  java
  • 先序遍历递归创建二叉树

    #include "stdio.h"
    #include "stdlib.h"
    typedef struct TNode{   //树节点
        char data;
        TNode *lchild,*rchild;
    }TNode;
    typedef struct LNode{  //栈节点
        char data;
        LNode *next;
    }LNode;
    
    void push(LNode *&l,char data){   //入栈
        LNode *p = (LNode*)malloc(sizeof(LNode));
        p->data = data;
        p->next = l->next;
        l->next = p;
    }
    char pop(LNode *&l){  //出栈
        LNode *p = l->next;
        char tmp = p->data;
        l->next = p->next;
        free(p);
        return tmp;
    }
    
    TNode *CreateTree(LNode *&l){   //先序遍历建立二叉树,参数为数据栈l
        if(l->next->data=='*'){    //假如当前首字符为*,那就说明该节点为NULL,返回上一层的createTree函数,并运行上一层函数未运行完的语句
            pop(l);   //抛掉栈顶元素
            return NULL;
        }
        TNode *p = (TNode*)malloc(sizeof(TNode));   //申请新节点
        p->data = pop(l);   //栈顶元素入树
        p->lchild = CreateTree(l);   //将下一个树节点链接到当前节点的左子树上
        p->rchild = CreateTree(l);   
        return p; //当运行到这个语句的时候,说明树的创建已经完成了。把根节点返回
    }
    
    
    void preOrder(TNode *t){  //先序遍历
        if(t!=NULL){
            printf("%c ",t->data);
            preOrder(t->lchild);
            preOrder(t->rchild);
        }
    }
    void InOrder(TNode *t){  //中序遍历
        if(t!=NULL){
            InOrder(t->lchild);
            printf("%c ",t->data);
            InOrder(t->rchild);
        }
    }
    void postOrder(TNode *t){  //后序遍历
        if(t!=NULL){
            postOrder(t->lchild);
            postOrder(t->rchild);
            printf("%c ",t->data);
        }
    } 
    
    int main(){
        char str[] = {'A','B','C','*','*','D','E','*','G','*','*','F','*','*','*'};  //*表示空
        LNode *s = (LNode*)malloc(sizeof(LNode));
        s->next = NULL;
        for(int i=15;i>=0;i--) push(s,str[i]);  //将树数据入栈
        TNode *t = CreateTree(s);
        preOrder(t);
        InOrder(t);
        getchar();
        return 0;
    }

    代码中序列对应的树如下图:

  • 相关阅读:
    Understanding about Baire Category Theorem
    Isometric embedding of metric space
    Convergence theorems for measurable functions
    Mindmap for "Principles of boundary element methods"
    Various formulations of Maxwell equations
    Existence and uniqueness theorems for variational problems
    Kernels and image sets for an operator and its dual
    [loj6498]农民
    [luogu3781]切树游戏
    [atAGC051B]Three Coins
  • 原文地址:https://www.cnblogs.com/BreezeFeng/p/14026469.html
Copyright © 2011-2022 走看看