首页 > 其他 > 详细

平衡二叉树

时间:2017-11-05 23:03:56      阅读:282      评论:0      收藏:0      [点我收藏+]

技术分享

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/


class Solution {
public:
  /*
  * @param root: The root of binary tree.
  * @return: True if this Binary tree is Balanced, or false.
  */
  int depth(TreeNode *root) {
  if (root == NULL) {
    return 0;

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

  }
  int lft = depth(root->left);
  int rit = depth(root->right);
  return max(lft , rit) + 1;
  }
  bool isBalanced(TreeNode *root) {
    if (root == NULL) {
      return 1;

    }
  int lft = depth(root->left);
  int rit = depth(root->right);
  if (abs(lft-rit) <=1) {
    return isBalanced(root->left)&&isBalanced(root->right);

  }
  else
    return 0;
  }
};

平衡二叉树

原文:http://www.cnblogs.com/ye-chen/p/7789186.html

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