求二叉树高度的c语言函数,计算二叉树的高度(深度) C/C++

二叉树递归特性可以计算出二叉树高度:

不多逼逼,code:

#includeusing namespace std;

typedef struct BinaryTreeNode

{

char data; //数据

struct BinaryTreeNode *left; //左孩子

struct BinaryTreeNode *right; //右孩子

}Node;

int getDepth(Node *root)

{

if (NULL == root)

{

return 0;

}

int leftDepth = getDepth(root->left); // 计算左子树的高度,如果为NULL,高度为0

int rightDepth = getDepth(root->right); // 计算右子树的高度,如果为NULL,高度为0

int treeDepth = leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;

return treeDepth;

}

int main()

{

//准备数据

Node nodeA = { 'A',NULL,NULL };

Node nodeB = { 'B',NULL,NULL };

Node nodeC = { 'C',NULL,NULL };

Node nodeD = { 'D',NULL,NULL };

Node nodeE = { 'E',NULL,NULL };

Node nodeF = { 'F',NULL,NULL };

Node nodeG = { 'G',NULL,NULL };

//建立关系

nodeA.left = &nodeB;

nodeA.right = &nodeC;

nodeB.left = &nodeD;

nodeB.right = &nodeE;

nodeC.left = &nodeF;

nodeC.right = &nodeG;

//调用函数

int depth = getDepth(&nodeA);

printf("二叉树的深度为:%d\n", depth);

system("pause");

return 0;

}

二叉树,还是这棵二叉树:

67b0c899b4a6b014be4dbd0d59f5f237.png

运行结果:

bdf39cc978b4324b974d3695d4473044.png

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值