您的位置:首页 > 编程语言 > C语言/C++

c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)及运行实例结果

2017-12-24 00:50 681 查看
这是算法导论中二叉树搜索的一个题

二叉树如图所示



c++代码

#include<iostream>
#define N 7
using namespace std;

//定义节点
class node
{
public:
int data;
node *leftChild;//指针
node *rightChild;
};
typedef node *BiTree;//等价

node *createNode(int value)//创建节点,返回类型指针型,所以加*
{
node * q = new node;
q->leftChild = NULL;//leftChild指针为空
q->rightChild = NULL;
q->data = value;

return q;
}

BiTree createBiTree()
{
node *p
= {NULL};
int array[6]={6,5,7,2,5,8};//输入的二叉树
for(int i=0;i<6;++i)
p[i] = createNode(array[i]);
for(int i = 0; i < N/2; i++)
{
p[i]->leftChild = p[i * 2 + 1];
p[i]->rightChild = p[i * 2 + 2];
}

return p[0];
}
//访问节点中的数据
int visit(BiTree tree)
{
return tree->data;
}
// 先序遍历
void preorderTreeWalk(BiTree tree)
{
if(tree)
{
cout << visit(tree) << " ";
preorderTreeWalk(tree->leftChild);
preorderTreeWalk(tree->rightChild);
}
}
// 中序遍历
void inorderTreeWalk(BiTree tree)
{
if(tree)
{
inorderTreeWalk(tree->leftChild);
cout << visit(tree) << " ";
inorderTreeWalk(tree->rightChild);
}
}
// 后序遍历
void postorderTreeWalk(BiTree tree)
{
if(tree)
{
postorderTreeWalk(tree->leftChild);
postorderTreeWalk(tree->rightChild);
cout << visit(tree) << " ";
}
}

int main()
{
BiTree tree = createBiTree();
cout << "先序遍历结果为:";
preorderTreeWalk(tree);
cout << endl;
cout << "中序遍历结果为:";
inorderTreeWa
ae65
lk(tree);
cout << endl;
cout << "后序遍历结果为:";
postorderTreeWalk(tree);
cout << endl;

return 0;
}


运行结果

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