二叉链表的基本操作

#include

using namespace std;

struct node
{
    node *lChild;
    node *rChild;
    char data; 
};
//先序递归创建树 
node *createTree()
{
    char ch;
    cin>>ch;
    node *root;
    if(ch=='#')
    {
        return NULL;
    }
    else
    {
        root=new node();
        root->data=ch;
        root->lChild=createTree();
        root->rChild=createTree();
        return root;
    }
}
//先序打印 
void print(node *t)
{
    if(t)
    {
        cout<data<<" ";
        print(t->lChild);
        print(t->rChild);
    }
}
//结点个数 
int countNode(node *t)
{
    if(t==NULL)
    {
        return 0;
    }
    else
    {
        return countNode(t->lChild) + countNode(t->rChild)+1;
    }
}
//叶子个数 
int countLeaf(node *t)
{
    if(t==NULL)
    {
        return 0;
    }
    else if(t->lChild==NULL && t->rChild==NULL)
    {
        return 1;
    }

    return countLeaf(t->lChild) + countLeaf(t->rChild); 
}
//树的高度 
int getHeight(node *t)
{
    int l,r;
    if(t==NULL)
    {
        return 0;
    }
    else
    {
        l=getHeight(t->lChild);
        r=getHeight(t->rChild);
        return (l>r)?(l+1):(r+1);
    }
}
//按树状结构打印
void printTree(node *t,int h)
{
    if(t==NULL)
    {
        return;
    }
    printTree(t->rChild,h+1);
    for(int i=1;icout<<" ";
    } 
    cout<data<lChild,h+1);
} 
//层序遍历 
void levelOrderPrint(node *t)
{
    if(t==NULL)
    {
        return;
    }
    node *queue[100];
    int front=-1,rear=-1;
    queue[++rear]=t;

    while(front!=rear)
    {
        front++;
        cout<<queue[front]->data;
        if(queue[front]->lChild!=NULL)
        {
            queue[++rear]=queue[front]->lChild;
        }
        if(queue[front]->rChild!=NULL)
        {
            queue[++rear]=queue[front]->rChild;
        }
    }

}
//双亲节点 
char parent(node *t,char n)
{

    if(t==NULL||t->data==n)
    {
        return 0;
    }
    if(t->lChild && t->lChild->data==n)
    {
        return t->data;
    }
    if(t->rChild && t->rChild->data==n)
    {
        return t->data;
    }
    char val = parent(t->lChild,n);
    if(val!=0)
    {
        return val;
    }
    else 
    {
        return parent(t->rChild,n);
    }
}
//销毁 
void destroyTree(node * (& t))
{
    if(t)
    {
        destroyTree(t->lChild);
        destroyTree(t->rChild);
        delete t;
        t=NULL;
    }
} 
int main()
{
    node *t=NULL;
    t=createTree();
    print(t);
    cout<1);
    cout<cout<cout<cout<cout<cout<'4')<return 0;
}

你可能感兴趣的:(数据结构)