二叉树的基本使用

创建树。前序遍历,中序遍历,后序遍历。查找二叉树结点个数,查找二叉树叶子结点个数,查找二叉树度数为1的结点的个数



#include "iostream"
using namespace std;

struct tree
{
    int data;
    tree *left,*right;
};

class Tree
{
    static int n;
    static int m;
public:
    tree *root;
    Tree()
    {
        root=NULL;
    }
    void create_Tree(int);
    void preorder(tree *);
    void inorder(tree *);
    void postorder(tree *);
    int count(tree *);
    int findleaf(tree *);
    int findnode(tree *);
};

int Tree::n=0;
int Tree::m=0;

void Tree::create_Tree(int x)
{
    tree *t;
    t=new(tree);
    t->data=x;
    t->left=t->right=NULL;

    if (root==NULL)
        root=t;
    else
    {
        tree *last;
        tree *now=root;
        while (now!=NULL)
        {
            last=now;
            if (x<now->data)
                now=now->left;
            else
                now=now->right;
        }
        if (x<last->data)
            last->left=t;
        else
            last->right=t;
    }
}

int Tree::count(tree *p)
{
    if (p==NULL) return 0;
    else
        return count(p->left)+count(p->right)+1;
}

int Tree::findleaf(tree *p)
{
    if (p==NULL) return 0;
    else
    {
        if (p->left==NULL && p->right==NULL) return n+=1;
        else
        {
            findleaf(p->left);
            findleaf(p->right);
        }
        return n;
    }
}

int Tree::findnode(tree *p)
{
    if (p==NULL) return 0;
    else
    {
        if (p->left!=NULL && p->right!=NULL)
        {
            findnode(p->left);
            findnode(p->right);
        }
        if (p->left!=NULL && p->right==NULL)
        {
            m+=1;
            findnode(p->left);
        }
        if (p->left==NULL && p->right!=NULL)
        {
            m+=1;
            findnode(p->right);
        }
    }
    return m;
}

void Tree::preorder(tree *p)
{
    if (p!=NULL)
    {
        cout<<p->data<<" ";
        preorder(p->left);
        preorder(p->right);
    }
}

void Tree::inorder(tree *p)
{
    if (p!=NULL)
    {
        preorder(p->left);
        cout<<p->data<<" ";
        preorder(p->right);
    }
}

void Tree::postorder(tree *p)
{
    if (p!=NULL)
    {
        postorder(p->left);
        postorder(p->right);
        cout<<p->data<<" ";
    }
}
int main()
{
    Tree A;
    int n,x;
    cout<<"输入点个数:";
    cin>>n;
    cout<<"输入"<<n<<"个数字: ";
    while (n--)
    {
        cin>>x;
        A.create_Tree(x);
    }

    cout<<"二叉树结点个数:"<<A.count(A.root)<<endl;
    cout<<"二叉树叶子节点个数:"<<A.findleaf(A.root)<<endl;
    cout<<"二叉树中度数为1的结点的数量为:"<<A.findnode(A.root)<<endl;
    cout<<endl<<"先序遍历序列:"<<endl;
    A.preorder(A.root);
    cout<<endl<<"中序遍历序列:"<<endl;
    A.inorder(A.root);
    cout<<endl<<"后序遍历序列:"<<endl;
    A.postorder(A.root);

    return 0;
}


posted @ 2017-07-07 15:58  gccbuaa  阅读(278)  评论(0编辑  收藏  举报