leetcode之Balanced Binary Tree
来源:互联网 发布:淘宝上的众筹是真的吗 编辑:程序博客网 时间:2024/06/07 20:52
采用递归思想,递归的结束条件尤其要注意。当左右子树的深度之差的绝对值>1,就一定不是平衡二叉树。注意的是,讲条件反过来说,左右子树的深度之差绝对值<=1,也不一定是平衡二叉树!!这一点要绝对注意!!
(1)C++实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int depth(TreeNode* p){
if(p == NULL)
return 0;
return 1+max(depth(p->left),depth(p->right));
}
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
if(root->left == NULL && root->right == NULL)
return true;
if(abs(depth(root->left)-depth(root->right))>1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
};
(2)java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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(depth(root.left)-depth(root.right))>1)
return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int depth(TreeNode tr){
if(tr == null)
return 0;
return 1+Math.max(depth(tr.left), depth(tr.right));
}
}
- LeetCode 之 Balanced Binary Tree
- LeetCode之Balanced Binary Tree
- leetcode之Balanced Binary Tree
- leetcode 之 Balanced Binary Tree
- LeetCode之Balanced Binary Tree
- leetcode之Balanced Binary Tree
- leetcode之Balanced Binary Tree
- leetcode之Balanced Binary Tree
- LeetCode 之 Balanced Binary Tree
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- 网页元素的滑动事件(三)
- OpenJ_Bailian - 3421
- VS集成Qt环境搭建
- 用JS实现图片轮播
- 插入排序
- leetcode之Balanced Binary Tree
- java实现AVL树(一种自平衡二叉树)数据结构
- Jsp(1)jsp基础
- Spring MVC 拦截器的讲解
- iOS开发之理解iOS中的MVC设计模式
- LeetCode之9---Palindrome Number
- Linux c 目录操作函数scandir
- 从六人中选出几人参加任务
- 【LetCode 算法修炼】Add Two Numbers