二叉树的建立-遍历-求树高

二叉树的建立-遍历-求树高

程序实现:

#include <iostream>

using namespace std;

//定义一个树结构
typedef struct  Btree
{
    int num;
    struct Btree *lchild;
    struct Btree *rchild;
}Btree,*PBtree;

//获取最大值
int get_max(int a,int b)
{
    return a>b?a:b;
}

//树的建立
PBtree createTree(PBtree root,int data)
{
    PBtree newNode=NULL;
    newNode =new Btree();
    newNode->num=data;
    newNode->lchild=NULL;
    newNode->rchild=NULL;

    if(root==NULL)
    {
        root=newNode;
        return root;
    }
    else
    {
        PBtree pback=NULL;
        PBtree pcur=root;
        while(pcur!=NULL)
        {
            pback=pcur;

            if(pcur->num>data)
                pcur=pcur->lchild;
            else if(pcur->num<data)
                pcur=pcur->rchild;
            else
            {
                delete newNode;
                return pcur;
            }
        }
        if(pback->num>data)
            pback->lchild=newNode;
        else
            pback->rchild=newNode;
        return pback;
    }
}

//先序遍历
void preorder( PBtree root)
{
    if(root==NULL)
        return;
    else
    {
        preorder(root->lchild);
        preorder(root->rchild);
        cout<<root->num<<" ";
    }
}
//中序遍历
void inorder( PBtree root)
{
    if(root==NULL)
        return;
    else
    {
        inorder(root->lchild);
        cout<<root->num<<" ";
        inorder(root->rchild);
    }
}

//二叉树种结点的个数
int count_tree(PBtree root)
{

    if(root==NULL)
        return 0;
    else
    {
        return count_tree(root->lchild)+count_tree(root->rchild)+1;
    }
}

//计算树的高度
int high_tree(PBtree root)
{
    if(root==NULL)
        return 0;
    else
        return get_max(high_tree(root->lchild)+1,high_tree(root->rchild)+1);
}

//后续遍历
void postorder( PBtree root)
{
    if(root==NULL)
        return;
    else
    {
        postorder(root->lchild);
        postorder(root->rchild);
        cout<<root->num<<" ";
    }
}

int main()
{
    PBtree root=NULL;
    root=createTree(root,6);
    for(int i=0;i<10;i++)
        createTree(root,i);
    preorder(root);
    cout<<endl;
    inorder(root);
    cout<<endl;
    postorder(root);
    cout<<endl;
    cout<<high_tree(root)<<endl;
    cout<<count_tree(root)<<endl;
    return 0;
}

输出结果:

5 4 3 2 1 0 9 8 7 6
0 1 2 3 4 5 6 7 8 9
5 4 3 2 1 0 9 8 7 6
7
10

猜你喜欢

转载自blog.csdn.net/u013069552/article/details/81216612