4.3&4.4二叉树的链式存储和遍历

// DataStructTest.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream.h>
#include 
<malloc.h>

typedef 
struct btnode * bitreptr;

struct btnode
{
    
char data;                    //数据
    bitreptr lchild;            //左节点指针
    bitreptr rchild;            //右节点指针
}
;

//建立一个树,与书中P84中的是一样的,函数返回一个树的头指针
bitreptr CreateTree()            
{
    bitreptr A,B,C,D,E,F;
    bitreptr nodes[
6];
    
for(int i=0;i<6;i++)
    
{
        nodes[i]
=(bitreptr)malloc(sizeof(btnode));
        nodes[i]
->lchild=NULL;
        nodes[i]
->rchild=NULL;
    }

    A
=nodes[0];
    B
=nodes[1];
    C
=nodes[2];
    D
=nodes[3];
    E
=nodes[4];
    F
=nodes[5];

    A
->data='A';
    A
->lchild=B;
    A
->rchild=E;

    B
->data='B';
    B
->lchild=C;
    B
->rchild=D;

    C
->data='C';

    D
->data='D';

    E
->data='E';
    E
->rchild=F;

    F
->data='F';

    
return A;
}


void visit(const bitreptr node)
{
    cout
<<node->data<<endl;;
}


//先根遍历
void preorder(const bitreptr root)
{
    bitreptr node
=root;
    
if (node!=NULL)
    
{
        visit(node);
        preorder(node
->lchild);
        preorder(node
->rchild);
    }

}

//中根遍历
void inorder(const bitreptr root)
{
    bitreptr node
=root;
    
if (node!=NULL)
    
{
        inorder(node
->lchild);
        visit(node);
        inorder(node
->rchild);
    }

}

//后根遍历
void postorder(const bitreptr root)
{
    bitreptr node
=root;
    
if (node!=NULL)
    
{
        postorder(node
->lchild);
        postorder(node
->rchild);
        visit(node);
    }

}

//计算叶子的数目
void countleaf(const bitreptr t,int & count)
{
    
if (t!=NULL)
    
{
        
if (t->lchild==NULL &&t->rchild==NULL)
            count
++;
        countleaf(t
->lchild,count);
        countleaf(t
->rchild,count);
    }

}


int main(int argc, char* argv[])
{
    bitreptr root;
    
//建立树
    root=CreateTree();
    
//
    cout<<"先根遍历"<<endl;
    preorder(root);
    
//
    cout<<"中根遍历"<<endl;
    inorder(root);
    
//
    cout<<"后根遍历"<<endl;
    postorder(root);
    
//
    cout<<endl;
    
int count=0;
    countleaf(root,count);
    cout
<<"页子的数量为:"<<count<<endl;
    
return 0;
}

posted @ 2007-07-09 11:10  吴东雷  阅读(601)  评论(0编辑  收藏  举报