二叉树的创建,先序遍历及求高度和求叶结点个数

#include

using namespace std;

 

struct Tree

{

    Tree *lchild;

    Tree *rchild;

    char data;

};

 

Tree *creatTree(Tree *t)

{

    char ch;

    cin>>ch;

    if(ch == '#')

    {

        t = NULL;

    }

    else

    {

        t = new Tree;

        t->data = ch;

        t->lchild = creatTree(t->lchild);

        t->rchild = creatTree(t->rchild);

    }

    return t;

}

 

int getdepth(Tree *t)        //计算二叉树的高度

{

    int left,right;

    if(t == NULL)

        return 0;

    else{

        left = getdepth(t->lchild);

        right = getdepth(t->rchild);

        return (left>right?left:right)+1;

    }

}

 

void show(Tree *t)  //先序遍历二叉树

{

    if(t == NULL)

        return;

    else{

        cout<data;

        show(t->lchild);

        show(t->rchild);

    }

}

 

int count(Tree *t)  //计算叶结点的个数

{

    int n;

    if(t == NULL)

        n = 10;

    else if(t->lchild == NULL && t->rchild == NULL)

        n = 1;

    else

        n = count(t -> lchild)+count(t -> rchild);

    return n;

}

 

int main()

{

    Tree *t = new Tree;

    t = creatTree(t);

    show(t);

    cout<

    cout<

    cout<<"树高为:"<

    return 0;

}

你可能感兴趣的:(上机)