二叉链表的基本操作
来源:互联网 发布: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
- 数据结构--二叉链表的基本操作
- 二叉链表的基本操作
- 二叉树的基本操作 (二叉链表实现)
- 二叉链表的定义与基本操作实现函数
- 二叉树二叉链表实现基本操作
- 二叉树的构造(二叉链表)、遍历以及基本操作
- c语言实现二叉树的基本操作--二叉链表存储
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- html 块级元素和行级元素
- QT串口读取数据
- 代码片段 URL
- svn安装并用eclipse集成
- IIS状态代码的含义
- 二叉链表的基本操作
- 强化学习介绍(Introduction to RL)
- vim配置
- 理解之后的模仿或者原有基础上的改造是对高效编程学习的最高效的方法
- ZJOI2017
- 超时时间的用途的理解和总结
- CDOJ(UESTC) 149 解救小Q(bfs中涉及传送带的问题)
- JavaWeb——response与request
- 代码设计程度的出发点是什么