首页 > 其他 > 详细

平衡二叉树

时间:2016-09-28 02:00:20      阅读:175      评论:0      收藏:0      [点我收藏+]

1、求二叉树的深度  递归

  int BitreeDepth(TreeNode *root){

    if(root == NULL) return 0;

    else if(root->left == NULL && root->right == NULL) return 1;

    int DepthTl = BitreeDepth(root->left);

    int DepthTr = BitreeDepth(root->right);

    return 1+max(DepthTl,DepthTr);

  }

2、求是否为平衡二叉树 递归

  bool isBalanced(TreeNode *root){

    if(root == NULL)  return true;

    if(sub_abs(BitreeDepth(root->left),BitreeDepth(root->right))>1) return flase;

    return isBalanced(root->left)&&isBalanced(root->right);
  }

3、tips 递归的思想:找结束条件 然后return;如在2中求是否为平衡二叉树,我们第二个if,找结束条件是sub_abs()>1,而不是找运行条件sub_abs()<=1;

   暗示,在sub_abs()<=1的情况下,函数没有完成,继续找左子树和右子树,再 return。

  

平衡二叉树

原文:http://www.cnblogs.com/codingtao/p/5914745.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!