(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); } }
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 第十周 项目一 (1)二叉树层次遍历算法的验证
- 按层次顺序(同一层自左至右)遍历二叉树的算法
- 【Lehr】【数据结构与算法】【C语言】二叉树的递归遍历
- C语言实现二叉树的常用的算法(递归与非递归实现遍历)
- 二叉树采用二叉链表结构表示。设计并实现如下算法:输入某棵二叉树的广义表形式,建立该二叉树,并按层次遍历该二叉树。
- 【Lehr】【数据结构与算法】【C语言】二叉树由两种遍历推出整棵树
- C语言二叉树常见操作详解【前序,中序,后序,层次遍历及非递归查找,统计个数,比较,求深度】
- 二叉树的遍历算法(C语言)
- 数据结构例程——二叉树的层次遍历算法
- 【简单算法】29.二叉树的层次遍历
- c语言实现二叉树先序,中序,后序(递归),层次遍历,求叶子节点个数及树的深度,下一篇写非递归的遍历
- 数据结构 c语言实现 二叉树的层次遍历(linux下实现)
- c语言实现二叉树层次遍历(借助队列实现)
- C语言基本数据结构之二(二叉树的三种遍历,节点数以及深度算法)
- 第十周 项目1 - 二叉树算法验证 (验证二叉树的层次遍历算法)
- 二叉树的深度优先,广度优先,以及层次遍历算法
- 二叉树的层次遍历及求节点个数的算法
- 结点遍历C语言实现二叉树的常用的算法(递归与非递归实现遍历)
- 【算法】二叉树的递归遍历C语言实现
- 第十一周--二叉树的层次遍历算法