数据结构 -- 树的遍历

一.树的结构和方法

//定义树节点的数据类型
typedef struct treeNode{
    int  data;
    struct treeNode* leftChild;
    struct treeNode* rightChild;
    int tag;
}treeNode;

//定义二叉树的数据类型
typedef struct bintree{
    treeNode *root;//记录根节点地址
}bintree;

//初始化结点
treeNode *node(int data){
    treeNode *node = (treeNode *)malloc(sizeof(treeNode));
    node->data = data;
    node->leftChild = NULL;
    node->rightChild = NULL;

    return node;
}

//初始化树
bintree *tree(treeNode *node){
    bintree *tree;
    tree = (bintree *)malloc(sizeof(bintree));
    tree->root = node;
    return tree;
}
//树插入左节点
void insertLeftNode(treeNode *fatherNode,treeNode*LeftNode){
    fatherNode->leftChild = LeftNode;
}
//树插入右节点
void insertRightNode(treeNode *fatherNode,treeNode*rightNode){
    fatherNode->rightChild = rightNode;
}

二.栈的结构与方法


//用链表定义栈
typedef struct SNode *stack;
struct SNode{
    treeNode *data;
    struct SNode *next;
};
//初始化栈
stack CreatStack(){
    stack S;
    S = (stack)malloc(sizeof(struct SNode));
    S->next = NULL;
    return S;
}
//判断栈是否空
int  stackIsEmpty(stack S){
    return (S->next == NULL);
}
//压栈
void Push(treeNode *node ,stack S){
    struct SNode *newNode;
    newNode = (struct SNode *)malloc(sizeof(struct SNode));
    newNode ->data = node;
    newNode->next = S->next;
    S->next = newNode;
}
//出栈
treeNode* Pop(stack S){

    if (stackIsEmpty(S)) {
        printf("空");
        return NULL;
    }else{
        struct SNode *newNode;
        treeNode *topElem;
        newNode = S->next;
        S->next = newNode->next;
        topElem = newNode->data;
        free(newNode);
        return topElem;
    }
}

三.队列的结构与方法

//链表定义队列
typedef struct queueNode{
    treeNode *data;
    struct queueNode *next;
}queueNode;

typedef struct LinkQueue{
    queueNode *rear;
    queueNode *front;
}LinkQueue;
//队列初始化
LinkQueue *createQueue(){
    LinkQueue *queue = (LinkQueue *)malloc(sizeof(LinkQueue));
    if (!queue) {
        printf("空间不足!\n");
        return NULL;
    }
    queue->front = NULL;
    queue->rear = NULL;
    return queue;
}
//判断队列是否空
int queueIsEmpty(LinkQueue* queue){
    return (queue->front == NULL);
}
//队列删除操作
treeNode *queueDelete(LinkQueue *queue){
    if (queueIsEmpty(queue)) {
        printf("队列空\n");
        return NULL;
    }

    queueNode *itempQueueNode = queue->front;
    treeNode *itemData;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值