您的位置:首页 > 编程语言 > C语言/C++

(c语言)给出二叉树的自下而上、从右到左的层次遍历算法

2020-04-05 18:18 447 查看

这个很容易想到
层次遍历是自上而下,从左到右,
说明将层次遍历出队列的元素入栈,最后出栈即可得
b本篇以根节点为8的二叉搜索树8、5、10、3、7、9、11为例

typedef struct Tree {
int Data;
struct Tree *Lc;
struct Tree *Rc;
}Btree;                             //树节点

typedef struct Node {
Btree *P1;
struct Node *rear;
}Nodes;                             //栈

typedef struct Q {
Btree *P3;
struct Q*next;
}Array;                             //队列

Btree *insert(Btree*Ntree, int a);//插入节点
void Push(Node**top, Btree*P2);   //压入栈
void Pop(Node**top);              //出栈
void Push2(Array**q, Btree*P);    //入队列
void Pop2(Array**head);           //出队列
void BLorder(Btree* Ntree) ;      //如题遍历
int main() {
int a;
Btree *Ntree;
Ntree = (Btree*)malloc(sizeof(struct Tree));
Ntree->Data=8;
Ntree->Lc = Ntree->Rc = NULL;
for (int i = 0; i < 6; i++) {
scanf("%d", &a);
Ntree=insert(Ntree, a);
}
BLorder(Ntree);
system("pause");
return 0;
}

void Push(Node**top, Btree*P2) {
Nodes*N;
N = (Nodes*)malloc(sizeof(struct Node));
N->P1 = (Btree*)malloc(sizeof(struct Tree));
N->P1 = P2;
N->rear =(*top);
(*top)= N;
}

void Pop(Node**top) {
Nodes*P;
P = (Nodes*)malloc(sizeof(struct Node));
P = *top;
(*top) = (*top)->rear;
free(P);
}

void Push2(Array**q, Btree*P){
Array*N;
N = (Array*)malloc(sizeof(struct Q));
N->P3 = P;
N->next = NULL;
(*q)->next = N;
*q = N;
}
void Pop2(Array**head) {
Array*N;
N = (Array*)malloc(sizeof(struct Q));
N = (*head);
(*head)= N->next;
free(N);
}
Btree *insert(Btree*Ntree, int a) {
if (!Ntree) {
Ntree = (Btree*)malloc(sizeof(struct Tree));
Ntree->Data = a;
Ntree->Lc = Ntree->Rc = NULL;
}
else if (a > Ntree->Data) {
Ntree->Rc = insert(Ntree->Rc, a);
}
else if (a < Ntree->Data) {
Ntree->Lc = insert(Ntree->Lc, a);
}

return Ntree;
}
void BLorder(Btree* Ntree) {
Btree *P;
P = Ntree;//用P来遍历
Array *head;//队列的头节点
head = (Array *)malloc(sizeof(struct Q));
head->next = NULL;
Array *tail;//队列的尾节点
tail = head;
Nodes*N;
N = (Nodes*)malloc(sizeof(struct Node));
N = NULL;
Nodes*top;//指向栈顶元素
top = N;
Push2(&tail, P); //将根节点入队列
while (head->next) { //当队列空时停止循环
Push(&top, head->next->P3);//将队列的头元素入栈
Pop2(&head);               //将队列的头元素出队列
if (P->Lc)
Push2(&tail, P->Lc);
if (P->Rc)
Push2(&tail, P->Rc);
if (head->next)
P = head->next->P3;    //使P指向队列的头节点
}
while (top) {
printf("%d\n", top->P1->Data);
Pop(&top);
}
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
我爱小白~ 发布了7 篇原创文章 · 获赞 0 · 访问量 99 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐