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