您的位置:首页 > 其它

【二叉树】建立 | 先序遍历 | 中序遍历 | 后序遍历 | 层次遍历

2019-02-15 12:06 246 查看
[code]#include<cstdio>
#include<stdlib.h>
#include<queue>

using namespace std;

typedef struct Node
{
char data;
Node *left;
Node *right;
}node; //指typdef struct Node node
//结构体定义新变量时必须struct+结构体名,上述语句让struct Node有个别名node

//先序建立二叉树
node* createT()
{
node *root;
char ch = getchar();
if(ch=='#') root = NULL; //'#'指空子树
else
{
root = new node;
root->data = ch;
root->left = createT();
root->right = createT();
}
return root;
}

//先序遍历
void preOrder(node *T)
{
if(T==NULL) return;
printf("%c ",T->data);
preOrder(T->left);
preOrder(T->right);
}

//中序遍历
void inOrder(node *T)
{
if(T==NULL) return;
inOrder(T->left);
printf("%c ",T->data);
inOrder(T->right);
}

//后序遍历
void postOrder(node *T)
{
if(T==NULL) return;
postOrder(T->left);
postOrder(T->right);
printf("%c ",T->data);
}

//层次遍历
void layerOrder(node *T)
{
//队列是node*而不是node
queue<node*> q;
q.push(T); //根元素入队
while(!q.empty())
{
node* top = q.front(); //取出队首元素
q.pop();
printf("%c ",top->data);
if(top->left) q.push(top->left); //左子树非空
if(top->right) q.push(top->right); //右子树非空
}
//无论是遍历还是建立,都不要忘了子树空不空的问题
}

int main()
{
node *T;
T = createT();
printf("先序遍历:");
preOrder(T);
printf("\n中序遍历:");
inOrder(T);
printf("\n后序遍历:");
postOrder(T);
printf("\n层次遍历:");
layerOrder(T);
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐