Frankjunyu 2015-10-29 06:52 采纳率: 58.8%
浏览 1529
已采纳

c语言二叉树问题,代码不太理解,求大神解释,急

问题:A Binary Tree is called balanced if, for each node in the tree, the height of its left and right subtrees differ by no more than one. Write a function
int height_if_balanced( Tnode *root )
which returns -1 if the tree is not balanced, and returns the height of the tree, if it is balanced.

代码:

int height_if_balanced( Tnode *root )
{
int leftHeight, rightHeight, heightDiff;

if( root == NULL ) {
return 0; // tree is empty
}

leftHeight = height_if_balanced( root->left );
rightHeight = height_if_balanced( root->right );

if( leftHeight == -1 || rightHeight == -1 ) {
// if either the left or right subtree is unbalanced,
return -1 ; // then the whole tree is unbalanced
}

heightDiff = leftHeight - rightHeight;

if( heightDiff < -1 || heightDiff > 1 ) {
return -1; // tree is unbalanced
}

// tree is balanced, so we return its height
if( heightDiff > 0 ) {
return( leftHeight + 1 );
}
else {
return( rightHeight + 1 );
}
}

  • 写回答

1条回答 默认 最新

  • cxlovu 2015-10-29 09:46
    关注

    其实这个英文注解很清楚了,这个函数的功能是判断这棵二叉树是否为平衡的
    所谓的平衡是指两边子树的高度之差绝对值不大于1
    height_if_balanced()这个函数如果二叉树是平衡的输出高度(取左右子树中高度加大的),否则输出-1
    然后height_if_balanced()是一个递归函数,一层一层下去直到叶子节点跳出,最后返回高度
    纯手打, 还有什么不懂的地方再问吧

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!