【c语言】构建二叉树并前序遍历

#include 
#include 

#define SIZE        50
//数的结点结构
typedef struct NODE{
    int data;
    struct NODE *left,*right;
}Node;

typedef struct stack{
    int top;
    Node *db[SIZE];//保存树的结点
}stack;

Node *creat_tree(void)
{
    Node *t;
    int x;
    scanf("%d",&x);
   
    if(x == 0)
        t = NULL;
    else{
        t = (Node*)malloc(sizeof(Node));
        t ->data  = x;
        printf("输入%d结点的左子结点:",t->data);
        t->left = creat_tree();
        printf("输入%d结点的右子结点:",t->data);
        t->right = creat_tree();

    }
    return t;
}


//非递归实现前序遍历二叉树

void preVisit(Node *T)
{
//初始化栈
    stack *s = (stack*)malloc(sizeof(stack));
    s->top = 0;
   
    while(T || s->top > 0){
    if(T){
        printf("3%d",T->data);
        s->db[s->top++] = T;
        T = T->left;
        }
    else{
        T = s->db[--s->top];
        T = T->right;
        }
    }
   
}

//递归实现前序遍历
/*
void preVisit(Node *T)
{
    if(T){
        printf("%d",T->data);
        preVisit(T->left);
        preVisit(T->right);
   
    }

}
*/
int main(void)
{
    Node *T = NULL;

    printf("二叉数的建立,以输入‘0’结束\n");
    printf("输入根结点: ");
    T = creat_tree();
    printf("二叉树建立完毕\n");

    printf("前序遍历二叉树: \n");
    preVisit(T);

    return 0;

}

 

你可能感兴趣的:(数据结构,c语言,二叉树)