二叉树的基本使用
来源:互联网 发布:js作用域链和原型链 编辑:程序博客网 时间:2024/06/05 14:07
创建树,前序遍历,中序遍历,后序遍历,查找二叉树结点个数,查找二叉树叶子结点个数,查找二叉树度数为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;}
0 0
- 二叉树的基本使用
- Chapter8:二叉树的基本使用
- 二叉树的基本性质及使用实现
- 二叉树的基本操作 【二叉树】
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本运算
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- MPICH2在windows7下的并行计算与拓展项目
- I/O流实现图片压缩
- 单链表翻转的几种写法
- 移植u-boot-2015.07-rc3之修改代码支持串口(三)
- jquery下的ajax
- 二叉树的基本使用
- SSM的maven项目
- window上安装 MongoDB PHP扩展
- Altium Designer静态标注的bug
- IO流
- 中文GCC
- 哈理工2015暑假集训 zoj 2975 Kinds of Fuwas
- 像素、分辨率、屏幕大小(屏幕适配必看)
- Oracle RAC安装过程中碰到的“坑”和关键点(二)