二叉链表的基本操作

来源:互联网 发布:get软件买到假鞋 编辑:程序博客网 时间:2024/06/05 20:02
#include<iostream>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<<t->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;i<h;i++)    {        cout<<" ";    }     cout<<t->data<<endl;    printTree(t->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<<endl;    printTree(t,1);    cout<<endl;    cout<<countNode(t)<<endl;    cout<<countLeaf(t)<<endl;    cout<<getHeight(t)<<endl;    levelOrderPrint(t);    cout<<endl;    cout<<parent(t,'4')<<endl;    destroyTree(t);    print(t);    return 0;}
0 0