LintCode 平衡二叉树
来源:互联网 发布:excel两表格数据对比 编辑:程序博客网 时间:2024/06/06 01:09
1.描述
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
给出二叉树 A={3,9,20,#,#,15,7}
, B={3,#,20,15,7}
A) 3 B) 3 / \ \ 9 20 20 / \ / \ 15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
2.分析
判断一颗二叉树是否是平衡二叉树,关键在于是否每一个节点都是平衡的。首先根节点开始,只有根节点是平衡的,才依次往下层进行查找。
这里用到一个之前用过的hight函数判断一棵树的最大高度,而一个节点的平衡因子即为它的左右子树的最大高度之差,这样就可以得到当前节点的平衡因子。
若当前节点是平衡点,通过递归依次向下判断是否所有节点都平衡,直到叶子节点为止全部平衡这棵树即为平衡二叉树。
3.代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
int height(TreeNode *root)
{
int lheight,rheight;
if(root==NULL) return 0;
lheight=height(root->left);
rheight=height(root->right);
if(lheight>rheight)
return lheight+1;
else return rheight+1;
}
bool dfs(TreeNode *root)
{
if(root==NULL) return true;
int h;
h=height(root->left)-height(root->right);//当前节点的左右最大深度之差,即平衡因子
if(fabs(h)>1)
return false;
else return dfs(root->left)&&dfs(root->right);
}
bool isBalanced(TreeNode * root) {
// write your code here
return dfs(root);
}
};
4.总结
当有节点不平衡时,即返回一个false,之后无论其他节点是否平衡最终都为false。只有当目前为止所有的节点都平衡时才继续递归下去,出口设置为
叶子节点,直到所有的叶子节点也是平衡的最后才判断这棵树为平衡二叉树。
- LintCode:平衡二叉树
- 平衡二叉树,lintcode
- lintcode平衡二叉树
- LintCode 平衡二叉树
- 平衡二叉树-LintCode
- lintcode--平衡二叉树
- 平衡二叉树-LintCode
- LintCode 平衡二叉树
- lintcode-平衡二叉树 -93
- LintCode 93-平衡二叉树
- LintCode | 93. 平衡二叉树
- LintCode | 93. 平衡二叉树
- LintCode 93.平衡二叉树
- lintcode balanced-binary-tree 平衡二叉树
- Lintcode-递归-93 平衡二叉树
- LintCode之93 平衡二叉树
- 【LintCode-93】平衡二叉树(Java实现-递归算法)
- 平衡二叉树平衡法则
- 爬虫实例(二)——中国大学排名爬虫
- 一站式学习Wireshark(二):应用Wireshark观察基本网络协议
- cadence原理图库
- java中四种创建对象的方式
- wiringPi库API大全
- LintCode 平衡二叉树
- android RelativeLayout 内容居中解决办法
- SQilte/DataSet
- 打包遇到的bug Error:Error: Expected resource of type drawable [ResourceType]
- Android Viewpager切换焦点问题,ScrollView,ListView发生位移
- 无法解析的外部符号 _fprintf,该符号在函数 "unsigned int __cdecl gltLoadShaderPai
- [初学笔记] matlab连接字符串并在字符串中加空格及其他字符的操作(ASCII)
- MySQL SHOW命令
- Java使用File.separator解决Win和Linux的路径问题