69,373
社区成员
发帖
与我相关
我的任务
分享
//头文件
#ifndef __ERCHASHU_H__
#define __ERCHASHU_H__
struct node;
typedef struct tree
{
struct node *p_root;
}tree;
typedef struct node
{
int num;
// struct tree *p_left;
// struct tree *p_right;
tree left;
tree right;
}node;
void deinit(tree*);
//tree *search(tree*,int);
tree *search_new(tree*,int);
void insert_in_order(tree*,int);
int tjjd(tree*); //统计二叉树的节点数
int high(tree*);//计算二叉树的高度
#endif //__ERCHASHU_H__
//部分函数
//有序插入函数
void insert_in_order(tree *p_root,int num)
{
tree *p_tree=search_new(p_root,num);
if(!(p_tree->p_root))
{
node *p_tmp=(node*)malloc(sizeof(node));
if(p_tmp)
{
p_tmp->num=num;
p_tmp->left.p_root=NULL;
p_tmp->right.p_root=NULL;
p_tree->p_root=p_tmp;
}
}
}
//统计二叉树的节点数
int tjjd(tree *p_root)
{
int num=0;
if(!(p_root->p_root))
{
return 0;
}
num=tjjd(&(p_root->p_root->left));
num+=tjjd(&(p_root->p_root->right));
return num+1;
}
//计算二叉树的高度
int high(tree *p_root)
{
int left=0,right=0;
if(!(p_root->p_root))
{
return 0;
}
left=high(&(p_root->p_root->left));
right=high(&(p_root->p_root->right));
if(left>right||left==right)
{
return left;
}
else
{
return right;
}
}
//主函数(部分)
#include <stdio.h>
#include <stdlib.h>
#include "erchashu.h"
int main()
{
insert_in_order(&root,9);
insert_in_order(&root,5);
insert_in_order(&root,7);
insert_in_order(&root,3);
insert_in_order(&root,16);
insert_in_order(&root,8);
print(&root);
printf("\n");
printf("节点数为%d\n",tjjd(&root));
printf("树的高度为%d\n",high(&root));
}
int tjjd(node * n)
{
int count;
if(!n)
return 0;
count=1;
if(n->left)
count+=tjjd(n->left);
if(n->right)
count+=tjjd(n->right);
}
或者
int tjjd(node * n)
{
return n==NULL?0:1+tjjd(n->left)+tjjd(n->right);
}
高度也一样,一颗树的高度为max(左子树高度,右子树高度)+1(这个1也是根节点自身)
typedef struct node node;
#define max(a,b) ((a)<(b)?(b):(a))
int height(node *n)
{
return n==NULL?0:1+max(height(n->left),height(n->right));
}