Balanced Binary Tree
2016-06-04 16:19
246 查看
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.
思路:给定一棵树,判断这个树是不是平衡二叉树。平衡二叉树的定义如下:
(1)对于根节点root来说,其左右子树的高度差的绝对值小于等于1
(2)左子树为平衡的
(3)右子树为平衡的
代码如下:
/**
* 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) {
if(!root)
return true;
return fabs(getTreeHeigh(root->left)-getTreeHeigh(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
}
int getTreeHeigh(TreeNode *root) //返回一棵树的高度是多少
{
if(root==NULL)
return 0;
return max(getTreeHeigh(root->left),getTreeHeigh(root->right))+1;
}
};
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.
思路:给定一棵树,判断这个树是不是平衡二叉树。平衡二叉树的定义如下:
(1)对于根节点root来说,其左右子树的高度差的绝对值小于等于1
(2)左子树为平衡的
(3)右子树为平衡的
代码如下:
/**
* 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) {
if(!root)
return true;
return fabs(getTreeHeigh(root->left)-getTreeHeigh(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
}
int getTreeHeigh(TreeNode *root) //返回一棵树的高度是多少
{
if(root==NULL)
return 0;
return max(getTreeHeigh(root->left),getTreeHeigh(root->right))+1;
}
};
相关文章推荐
- js事件
- 自定义优惠券
- php字符串类型讲解
- AndroidL 导航栏控件使用说明
- c#基础--常量(const),只读字段(readonly)
- [修正] Berlin 10.1 支持 iPhone 4 (iOS v7.x)
- 微信开发流程及问题
- C++sqrt()函数与sqrtf()函数有什么区别?
- static的作用总结
- LeetCode-79.Word Search
- 如何在window下搭建 cocos2d-x-开发环境保罗各项配置
- deleteRow
- linux里的nvme驱动代码分析(加载初始化)
- Linux GCC常用命令
- Sd卡的存储与读取
- 字符串快速编写
- 2016-0604
- JAVA几种常见的编码格式
- Oracle 修改了 listener.ora 文件 在windows中的服务中启动,但是 lsnrctl status没有监听到数据库 xe或者是 orcl
- Eclipse新建工程没有minGW