初学数据结构二叉树求救
  • 板块学术版
  • 楼主Yuukiyo
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/3/20 22:04
  • 上次更新2024/3/21 12:58:52
查看原帖
初学数据结构二叉树求救
1318046
Yuukiyo楼主2024/3/20 22:04

想利用层次遍历初始化一棵二叉数,运行代码为什么没有输出啊!!!

#include <cstddef>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;


typedef struct BitNode {             //定义树
    int data;
    struct BitNode* lchild, * rchild;    //左右孩子节点                                      
} BitNode, * Bitree;

typedef struct Lnode {            //定义队列
    Bitree tree;
    struct Lnode* next;
}Lnode;
typedef struct LinkQueue {
    Lnode* front, * rear;
}LinkQueue;

LinkQueue Q;
Bitree root = new BitNode;


void initLinkQueue(LinkQueue Q);
void initBitNode(BitNode* root);
bool EnQueue(LinkQueue Q, Bitree tree);
Bitree DeQueue(LinkQueue Q);
void BitNode_cout(BitNode* root);

int main() {
    initLinkQueue(Q);
    initBitNode(root);
    EnQueue(Q, root);
    BitNode* l, * r;
    for (int i = 1; i <= 100; i++) {                //按层次遍历插入i
        if (Q.front->next->tree->lchild == NULL || Q.front->next->tree->rchild == NULL) {
            BitNode* parent = Q.front->next->tree;
            l = new BitNode;
            r = new BitNode;
            l->lchild = NULL;
            l->rchild = NULL;
            r->lchild = NULL;
            r->rchild = NULL;
            parent->lchild = l;
            parent->rchild = r;
            EnQueue(Q, l);
            EnQueue(Q, r);
            BitNode* parent_new = DeQueue(Q);
            parent_new->data = i;
        }
    }
    BitNode_cout(root);
    cin.get();
    return 0;
}


void initLinkQueue(LinkQueue Q) {    //初始化队列
    Q.front = new Lnode;
    Q.front->tree = NULL;
    Q.rear = Q.front;
    Q.front->next = NULL;
}
void initBitNode(BitNode* root) {
    root->data = 0;
    root->lchild = NULL;
    root->rchild = NULL;
}


bool EnQueue(LinkQueue Q, Bitree tree) {          //队列插入
    Lnode* q = new Lnode;
    if (q == NULL)
        return false;
    q->tree = tree;
    Q.rear->next = q;
    q->next = NULL;
    Q.rear = q;
    return true;
}
Bitree DeQueue(LinkQueue Q) {     //队列删除
    if (Q.front->next == NULL)
        return NULL;
    Bitree q = Q.front->next->tree;
    Lnode* l = Q.front->next;
    if (l->next == NULL)          //队列剩一个元素特殊处理
        Q.rear = Q.front;
    Q.front->next = l->next;
    delete l;
    return q;
}

void BitNode_cout(BitNode* root) {          //按层次遍历打印
    EnQueue(Q, root);
    BitNode* p = Q.front->next->tree;
    while (p->lchild != NULL || p->rchild != NULL) {
        EnQueue(Q, p->lchild);
        EnQueue(Q, p->rchild);
        BitNode* p_new = DeQueue(Q);
        cout << p_new->data;
        cout << "\n";
        p = Q.front->next->tree;
    }

}
2024/3/20 22:04
加载中...