二叉树遍历的应用--求叶数,非叶数,层数,所有数的和,查找某个数,插入
来源:互联网 发布:手机淘宝客服人工服务 编辑:程序博客网 时间:2024/05/16 01:23
#include <stdio.h>#include <stdlib.h>struct node{ int element; struct node* Left; struct node* Right;};struct node* CreateNode(int data){//创造新节点 struct node* temp; temp=(struct node*)malloc(sizeof(struct node)); if(temp!=NULL){ temp->element=data; temp->Left=NULL; temp->Right=NULL; } return temp;}struct node* FindNode(struct node* BinTree,int data)//查找{ if(BinTree==NULL) return NULL; if(BinTree->element==data) return BinTree; struct node* temp=NULL; if(BinTree->Left!=NULL) temp=FindNode(BinTree->Left,data); if(temp==NULL&&BinTree->Right!=NULL) temp=FindNode(BinTree->Right,data); return temp;}//假设每个节点值不同#define LEFT 1#define RIGHT 0struct node* InsertNode(struct node* BinTree,int loc,int dir,int data)//插入节点,loc代表插入的数的父节点的值,dir表示方向{ struct node* parent=FindNode(BinTree,loc); if(parent!=NULL){ struct node* temp=CreateNode(data); if(dir==LEFT) parent->Left=temp; else parent->Right=temp; } return BinTree;}int SumOfNode(struct node* BinTree)//求和{ if(BinTree==NULL) return 0; int sum=BinTree->element; if(BinTree->Left!=NULL) sum+=SumOfNode(BinTree->Left); if(BinTree->Right!=NULL) sum+=SumOfNode(BinTree->Right); return sum;}int CountOfLeaves(struct node* BinTree)//叶个数{ if(BinTree==NULL) return 0; if(BinTree->Left==NULL&&BinTree->Right==NULL) return 1; int count=0; if(BinTree->Left!=NULL) count+=CountOfLeaves(BinTree->Left); if(BinTree->Right!=NULL) count+=CountOfLeaves(BinTree->Right); return count;}int CountOfNotLeaves(struct node* BinTree)//非叶节点个数{ if(BinTree==NULL) return 0; if(BinTree->Left==NULL&&BinTree->Right==NULL) return 0; int count=1; if(BinTree->Left!=NULL) count+=CountOfNotLeaves(BinTree->Left); if(BinTree->Right!=NULL) count+=CountOfNotLeaves(BinTree->Right); return count;}int CountOfLevels(struct node* BinTree)//求层数{ if(BinTree==NULL) return 0; int count1=0,count2=0; if(BinTree->Left!=NULL) count1=CountOfLevels(BinTree->Left); if(BinTree->Right!=NULL) count2=CountOfLevels(BinTree->Right); return 1+(count1>count2?count1:count2);}int main(){ //手工建树,不提倡,之后会写到怎样建树 struct node* BinTree=CreateNode(10); BinTree=InsertNode(BinTree,10,1,20); BinTree=InsertNode(BinTree,10,0,30); BinTree=InsertNode(BinTree,30,1,40); BinTree=InsertNode(BinTree,40,0,50); return 0;}
1 0
- 二叉树遍历的应用--求叶数,非叶数,层数,所有数的和,查找某个数,插入
- 二叉树中查找和为某个数的所有路径
- 二叉树的实现和二叉数的遍历实现
- 二叉数的遍历
- 二叉数的遍历
- 树与图的应用:二叉树的构造、遍历和求叶子数和高度
- 递归与非递归下二叉查找数的插入·查找和删除
- 二叉查找树的插入与遍历
- 求二叉树中某个字符所在的层数
- 二叉树之查找指定节点所在的层数
- 二叉查找数 插入 删除
- 逆序数的二叉查找树统计
- JAVA二叉数的深度遍历和广度遍历
- 二叉树的【深/高度】【度为0/1/2的结点数】【遍历】【查找】【销毁】
- 二叉查找树的插入、删除、遍历和查找等C++实现
- 非递归层次遍历方法实现二叉树中指定节点的层次数查找
- 求某个数的所有因数
- 查找二叉查找树第N大的数
- 2016/10/25
- 闪屏页面
- SpringMVC传值操作
- 查找一个文件夹下指定后缀名文件的java方法
- Android性能优化之运算篇
- 二叉树遍历的应用--求叶数,非叶数,层数,所有数的和,查找某个数,插入
- 1016. 部分A+B (15)
- 驱动学习之输入子系统
- git常用指令整理
- sql server数据类型
- 从算法到编程——程序设计能力——C与C++
- jsp内置对象---response对象
- Java 基于UDP的Socket网络编程的入门及示例
- 【Selenium10】处理对话框