本文就二叉树的基本操作进行总结
包括二叉树的建立、递归遍历、非递归遍历、层序遍历等
二叉树的结构体如下
typedef struct _node { char data; struct _node* lchild; struct _node* rchild; }node;
1.二叉树的建立
void create(node*& tree) { char data; scanf("%c",&data); if ('#'==data) { tree=NULL; return; } tree=(node*)malloc(sizeof(node)); tree->data=data; printf("输入%c的左节点:",data); create(tree->lchild); printf("输入%c的右节点:",data); create(tree->rchild); }
void preOrder(node* tree) //先序递归遍历 { if(tree) { printf("%c",tree->data); preOrder(tree->lchild); preOrder(tree->rchild); } } void inOrder(node* tree) //中序递归遍历 { if(tree) { inOrder(tree->lchild); printf("%c",tree->data); inOrder(tree->rchild); } } void postOrder(node* tree) //后序递归遍历 { if(tree) { postOrder(tree->lchild); postOrder(tree->rchild); printf("%c",tree->data); } }
3.非递归遍历
非递归遍历利用队列实现
void preOrder1(node* tree) //先序非递归遍历 { deque<node*> q; node* t=tree; while (t!=NULL||!q.empty()) { while (t!=NULL) { printf("%c",t->data); q.push_back(t); t=t->lchild; } t=q.back(); q.pop_back(); t=t->rchild; } } void inOrder1(node* tree) //中序非递归遍历 { deque<node*> q; node* t=tree; while (t!=NULL||!q.empty()) { while (t!=NULL) { q.push_back(t); t=t->lchild; } t=q.back(); q.pop_back(); printf("%c",t->data); t=t->rchild; } } void postOrder1(node* tree) //后序非递归遍历 { deque<node*> q; node* t=tree; node* prerchild=NULL; while (t!=NULL||!q.empty()) { while (t!=NULL) { q.push_back(t); t=t->lchild; } t=q.back(); if (t->rchild==NULL||t->rchild==prerchild) { q.pop_back(); printf("%c",t->data); prerchild=t; t=NULL; } else { t=t->rchild; } } }
层序遍历也是借助队列实现的
void levelOrder(node* tree) { deque <node*> q; if (!tree) return; node* t=tree; q.push_back(t); while (!q.empty()) { t=q.front(); q.pop_front(); printf("%c",t->data); if (t->lchild) q.push_back(t->lchild); if (t->rchild) q.push_back(t->rchild); } }
void levelOrder1(node* tree) { deque<node*> q; if (NULL==tree) return; node* t=tree; q.push_back(t); int levelNum=1; while(!q.empty()) { levelNum=q.size(); for (int i=0;i<levelNum;i++) { t=q.front(); q.pop_front(); printf("%c",t->data); if (t->lchild!=NULL) { q.push_back(t->lchild); } if (t->rchild!=NULL) { q.push_back(t->rchild); } } printf("\n"); } }