Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

就是去查看一棵树是不是平衡的,一开始对平衡二叉树的理解有错误,所以写错了 ,看了别人的解答之后更正过来了:

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
int dep;
checkBalance(root, dep);
}
bool checkBalance(TreeNode * root, int &dep)
{
if(root == NULL){
dep = ;
return true;
}
int leftDep, rightDep;
bool isLeftBal = checkBalance(root->left, leftDep);
bool isRightBal = checkBalance(root->right, rightDep); dep = max(leftDep, rightDep) + ;
return isLeftBal && isRightBal && (abs(leftDep - rightDep) <= );
}
};

pS:感觉这个不应该easy的题目啊  想的时候头还挺疼的。。

用java的时候用上面的方法去做总是无法成功,所以换了一种方法,这个一开始没有想到,是看别人写的,代码如下所示:

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
if(root.left == null && root.right == null)
return true;
if(Math.abs(getDep(root.left) - getDep(root.right)) > 1)
return false;
return isBalanced(root.left) && isBalanced(root.right);
} public int getDep(TreeNode node){
if(node == null)
return 0;
else
return 1 + Math.max(getDep(node.left), getDep(node.right));
}
}

最新文章

  1. vim技巧
  2. FormatJS – 让你的 Web 应用程序国际化
  3. ESL python调用C模块时传递unicode字符串报错问题解决
  4. LeakCanary,检测安卓,java内存泄漏
  5. const和readonly你真的懂吗?
  6. svn+ssh
  7. setChecked方法触发onCheckedChanged监听器问题
  8. SharePoint 2013 APP 开发示例 (二)获取用户信息
  9. 二叉树最大路径和-Binary Tree Maximum Path Sum
  10. java-4-类和对象
  11. 解释代码((n &amp; (n-1))== 0)的含义
  12. 使用百度的富文本编辑器UEditor遇到的问题总结
  13. Linux 文件删除原理_009
  14. Study 7 —— CSS美化背景和边框
  15. cad2017卸载/安装失败/如何彻底卸载清除干净cad2017注册表和文件的方法
  16. 51Nod 1175 区间中第K大的数 (可持久化线段树+离散)
  17. 【Spark】SparkStreaming-Kafka-Redis-集成-基础参考资料
  18. ubuntu16.04后续工作
  19. golang io.ReadFull
  20. 当当网-前端project师測试题

热门文章

  1. springboot 常用的异常处理方式
  2. LeetCode-day04
  3. [String ] StringBuffer VS StringBuilder
  4. 自制Javascript浮动广告
  5. vim之可视化
  6. predis操作大全
  7. webbrowser控件——Windows下的开发利器
  8. 实用篇如何使用github(本地、远程)满足基本需求
  9. 013_HDFS文件合并上传putmarge功能(类似于hadoop fs -getmerge)
  10. 数独C语言算法