标签:遍历 malloc init 访问 二叉树 level return als 输入
用C/C++编写二叉树的前序遍历,中序遍历,后序遍历(递归)
使用辅助队列的层序遍历(非递归)
特别说明一下层次遍历:借助一个队列,先将二叉树根结点入队,然后出队,访问出队结点,若它有左子树,则将左子树根结点入队;若它有右子树,则将右子树树根结点入队。然后出队,访问出队结点.......如此反复,直至队列为空
#include <iostream> using namespace std; typedef struct BiTNode {//二叉树结构体 int data; struct BiTNode* lchild, * rchild; }BiTNode, * BiTree; typedef struct LinkNode {//下边两个结构体是队列
//由于下一行用到了BiTree结构体,所以应该把二叉树结构体BiTNode放在前,队列结构体放在后,否则VS2019报错 BiTree tree; struct LinkNode *next; }; typedef struct LinkQueue { LinkNode * front, * rear; }; void initQueue(LinkQueue &q) { q.front = q.rear = (LinkNode*)malloc(sizeof(LinkNode)); q.front->next = NULL; } bool isEmpty(LinkQueue q) { return q.front == q.rear ? true : false; } void EnQueue(LinkQueue &q, BiTree t) { //cout << "this is EnQueue:" << t->data <<",lchild:"<<t->lchild->data<<",rchild:"<<t->rchild->data<< endl; LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode)); p->tree = t; p->next = NULL; q.rear->next = p; q.rear = p; //cout << "in " << t->data << endl; } BiTree DeQueue(LinkQueue& q) { BiTree t; LinkNode* p = q.front->next; t = p->tree; //cout << endl; //cout << "quit " << t->data << endl; q.front->next = p->next; if (q.rear == p) q.rear = q.front; //这里不要写成q.front=q.rear,感谢Mr.Sunshine帮我改bug, free(p); return t; } BiTree init()//先序输入一个二叉树,输入0代表该树为空 { int dat; cin >> dat; if (dat == 0) return NULL; else { BiTree t = (BiTree)malloc(sizeof(BiTNode)); t->data = dat; t->lchild = init(); t->rchild = init(); return t; } } void PreOrder(BiTree t)//先序遍历 { if (t != NULL) { cout << t->data << " "; PreOrder(t->lchild); PreOrder(t->rchild); } } void InOrder(BiTree t)//中序遍历 { if (t != NULL) { InOrder(t->lchild); cout << t->data << " "; InOrder(t->rchild); } } void PostOrder(BiTree t)//后序遍历 { if (t != NULL) { PostOrder(t->lchild); PostOrder(t->rchild); cout << t->data << " "; } } void LevelOrder(BiTree t)//层序遍历,用队列辅助 { LinkQueue q; initQueue(q); BiTree temp; if (t == NULL) { cout << "树为空" << endl; } else { EnQueue(q,t); while (!isEmpty(q)) { temp=DeQueue(q); cout <<temp->data<<" "; if (temp->lchild != NULL) { EnQueue(q, temp->lchild); } if (temp->rchild != NULL) { EnQueue(q, temp->rchild); } } } } int main(void) { BiTree t = init();//建立二叉树,并输入 cout <<"前序遍历:"; PreOrder(t); cout << endl; cout << "中序遍历:"; InOrder(t); cout << endl; cout << "后序遍历:"; PostOrder(t); cout << endl; cout << "层次遍历:"; LevelOrder(t); cout << endl; }
前序输入二叉树:0表示结点为空NULL,1 2 4 0 0 5 0 0 3 0 0
运行:
标签:遍历 malloc init 访问 二叉树 level return als 输入
原文地址:https://www.cnblogs.com/murenma/p/13365546.html