#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#define MAXSIZE 100
using namespace std;
struct bitree{
char data;
struct bitree * lchild , *rchild ;
};
//先序创建二叉树
struct bitree * createbitree(){
char c ;
struct bitree *root ;
scanf("%c" , &c) ;
if(c == '#')
root = NULL ;
else{
root = (struct bitree *)malloc(sizeof(struct bitree) ) ;
root->data = c ;
root->lchild = createbitree() ;
root->rchild = createbitree() ;
}
return root ;
}
//前序遍历二叉树
void preorder(struct bitree *root){
if(root != NULL){
printf("%c\n" , root->data) ;
cout <<"root = " << root << endl;
preorder(root->lchild) ;
preorder(root->rchild) ;
}
}
//前序遍历来查找结点x的运算
//此算法有问题,因为无论如何算法都是完全遍历整个二叉树,就算找到了结点x,也无法返回结点x地址
//struct bitree* bisearch(struct bitree *root , char x){
// if(root == NULL)
// return NULL ;
// if(root->data == x){
// cout<<"return root = " << root << endl;
// return root ;
// }
// bisearch(root->lchild , x) ;
// bisearch(root->rchild , x) ;
//}
//求二叉树中的叶子节点数目,书上说是中序遍历,我认为是后序遍历
int countleaf(struct bitree * root){
if(root == NULL)
return 0 ;
int num = 0 , num1 , num2;
if(root ->lchild == NULL && root ->rchild == NULL)
num++ ;
else{
// num1 = countleaf(root->lchild) ;
// num2 = countleaf(root->rchild) ;
// num = num1 + num2 ;
num = countleaf(root->lchild) + countleaf(root->rchild) ;
}
return num ;
}
//后序遍历求二叉树的高度(节点的最大层数(层数从1开始))
int treedepth(struct bitree * root){
if(root == NULL)
return 0 ;
int h , lh , rh ;
lh = treedepth(root->lchild) ;
rh = treedepth(root->rchild) ;
if(lh >= rh)
h = lh +1 ;
else
h = rh+1 ;
return h ;
}
int main(){
struct bitree * root , *temp;
root = createbitree() ;
cout<<"前序遍历二叉树"<<endl;
preorder(root) ;
// cout<<"查找元素x"<< endl;
// temp = bisearch(root , 'D') ;
// cout<<"temp = " << temp << endl;
// if(temp == NULL)
// cout<<"无此元素" << endl;
// else
// cout<<"查找的元素为 :"<< temp->data << endl;
cout<<"二叉树的叶子节点数目" << endl;
int num = countleaf(root ) ;
cout<<"叶子节点数目 = " << num << endl;
cout<<"求二叉树的高度" << endl;
int depth = treedepth(root) ;
cout<<"二叉树高度 = " << depth << endl;
return 0 ;
}
求二叉树的叶子节点数目/二叉树的高度
最新推荐文章于 2021-03-13 20:45:58 发布