树-----求叶子结点数目,结点数目,树的高度

来源:互联网 发布:linux 服务器病毒查杀 编辑:程序博客网 时间:2024/04/26 12:43
/*求树的高度和结点数*/
#include<iostream>
#include<algorithm>
using namespace std;
int k = 0;
int m = 0;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {}
};


void num(TreeNode*t)//计算结点数目
{//递归去数,数完左边,数右边
if (t){
k++;
num(t->left);
num(t->right);
}
//传入的地址是根,操作的是子结点,返回的是与根节点相对应的右结点
}
int high(TreeNode*t)
{
if (t == NULL) return (0);
else
{
int hl = high(t->left);//左边多大
int hr = high(t->right);//右边多大
int h = max(hl,hr)+1; //加上根结点
return h;
}
}
void leaf(TreeNode*t1)
{
if (t1){
if (t1->left == NULL&&t1->right == NULL)
m++;
leaf(t1->left);
leaf(t1->right);
}
}//按照先序遍历,然后判断每个结点的左右结点
void main()
{
TreeNode t1(1);
TreeNode t2(2);
TreeNode t3(3);
TreeNode t4(4);
TreeNode t5(5);
TreeNode t6(6);
t1.left = &t2;
t1.right = &t3;
t2.left = &t4;
t2.right = &t5;
t3.left = &t6;
num(&t1);
cout << k << endl;
cout << high(&t1)<<endl;
leaf(&t1);
cout << m;
system("pause");
}
0 0
原创粉丝点击