#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 0
struct 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;
}