LeetCode OJ:Balanced Binary Tree(平衡二叉树)
2015-10-19 10:02
531 查看
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.
就是去查看一棵树是不是平衡的,一开始对平衡二叉树的理解有错误,所以写错了 ,看了别人的解答之后更正过来了:
pS:感觉这个不应该easy的题目啊 想的时候头还挺疼的。。
用java的时候用上面的方法去做总是无法成功,所以换了一种方法,这个一开始没有想到,是看别人写的,代码如下所示:
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 = 0; return true; } int leftDep, rightDep; bool isLeftBal = checkBalance(root->left, leftDep); bool isRightBal = checkBalance(root->right, rightDep); dep = max(leftDep, rightDep) + 1; return isLeftBal && isRightBal && (abs(leftDep - rightDep) <= 1); } };
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)); } }
相关文章推荐
- ppt幻灯片转换成pdf格式查看
- Linux下Nagios的安装与配置
- 【转载】MIMO技术杂谈(二):犹抱琵琶半遮面--MIMO信道中隐藏的秘密
- 单例模式探索
- 升级部署和修改
- 22.Power of Two
- HTML5_表单元素
- cocos2dx 常见的动作汇总
- QT总结(一)
- ArcGIS 通过 Excel 发布要素服务教程
- iOS7教程系列:自定义导航转场动画以及更多
- cocos2dx 使用Json(用于游戏更新)
- 接口继承和多态
- 【转载】MIMO技术杂谈(一):鱼与熊掌能否兼得?--浅谈分集与复用的权衡
- Coursera公开课笔记: 斯坦福大学机器学习第一课“引言(Introduction)”
- AFN —— unacceptable content-type: text/html"
- python中文编码
- 序列化容器—二进制编码与解码
- 蓝屏”的硬件原因及解决
- opencv 初级问题