首先需要一个结构体,表示每一个结点
typedef struct node {
char data; //结点存放的值
struct node* lchild; //指向左子树的指针
struct node* rchild; //指向右子树的指针
}BTnode;
然后就可以直接建树了
代码示例是按前序遍历(关于前序遍历后面有解释)建树
void build(BTnode* &T)
{
char data;
cin >> data;
T = new BTnode;
if (data == '#') //表示无输入
{
T = NULL;
return;
}
T->data = data;
T->lchild = NULL;
T->rchild = NULL;
build(T->lchild);
build(T->rchild);
}
二叉树有四种遍历方式
- 前序遍历:根节点->左子树->右子树
- 中序遍历:左子树->根节点->右子树
- 后序遍历:左子树->右子树->根节点
- 层序遍历:每一层分别遍历,直到最后的叶子节点被全部遍历完(需要队列来辅助)
void preOrder(BTnode* &T) //前序遍历
{
if (T)
{
cout << T->data << " ";
preOrder(T->lchild);
preOrder(T->rchild);
}
}
void inOrder(BTnode* &T) //中序遍历
{
if (T)
{
inOrder(T->lchild);
cout << T->data << " ";
inOrder(T->rchild);
}
}
void postOrder(BTnode* &T) //后序遍历
{
if (T)
{
postOrder(T->lchild);
postOrder(T->rchild);
cout << T->data << " ";
}
}
void levelOrder(BTnode* &T) //层序遍历
{
queue<BTnode*>q;
if (T == NULL) return;
q.push(T);
while (!q.empty())
{
BTnode* node = q.front();
q.pop();
cout << node->data << " ";
if (node->lchild) q.push(node->lchild);
if (node->rchild) q.push(node->rchild);
}
}
输入一个如图所示的二叉树
输出如图
整体代码展示
#include <iostream>
#include <cstdio>
#include <cstring>
#include<vector>
#include<string>
#include<queue>
using namespace std;
const int N = 1000;
typedef struct node {
char data;
struct node* lchild;
struct node* rchild;
}BTnode;
void build(BTnode* &T)
{
char data;
cin >> data;
T = new BTnode;
if (data == '#')
{
T = NULL;
return;
}
T->data = data;
T->lchild = NULL;
T->rchild = NULL;
build(T->lchild);
build(T->rchild);
}
void preOrder(BTnode* &T)
{
if (T)
{
cout << T->data << " ";
preOrder(T->lchild);
preOrder(T->rchild);
}
}
void inOrder(BTnode* &T)
{
if (T)
{
inOrder(T->lchild);
cout << T->data << " ";
inOrder(T->rchild);
}
}
void postOrder(BTnode* &T)
{
if (T)
{
postOrder(T->lchild);
postOrder(T->rchild);
cout << T->data << " ";
}
}
void levelOrder(BTnode* &T)
{
queue<BTnode*>q;
if (T == NULL) return;
q.push(T);
while (!q.empty())
{
BTnode* node = q.front();
q.pop();
cout << node->data << " ";
if (node->lchild) q.push(node->lchild);
if (node->rchild) q.push(node->rchild);
}
}
int main()
{
BTnode* root;
build(root);
cout << "前序遍历:";
preOrder(root);
cout << endl;
cout << "中序遍历:";
inOrder(root);
cout << endl;
cout << "后序遍历:";
postOrder(root);
cout << endl;
cout << "层序遍历:";
levelOrder(root);
cout << endl;
return 0;
}