c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)

来源:互联网 发布:网络带给我们的好处 编辑:程序博客网 时间:2024/05/18 01:02

这是算法导论中二叉树搜索的一个题

二叉树如图所示


c++代码

#include<iostream>#define N 7using 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[N] = {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 << "中序遍历结果为:";    inorderTreeWalk(tree);    cout << endl;    cout << "后序遍历结果为:";    postorderTreeWalk(tree);    cout << endl;    return 0;}

运行结果




阅读全文
0 0