leetcode 110 Balanced Binary Tree
2016-06-07 23:07
351 查看
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.
Subscribe to see which companies asked this question
class Solution {
public:
int balanced(TreeNode *root) {
if(root==NULL) {
return 0;
}
int left = balanced(root->left);
if(left==-1) return -1;
int right = balanced(root->right);
if(right==-1) return -1;
if(abs(left-right) > 1) return -1;
return max(left, right)+1;
}
bool isBalanced(TreeNode *root) {
if(root == NULL) return true;
int h = balanced(root);
return h!=-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.
Subscribe to see which companies asked this question
class Solution {
public:
int balanced(TreeNode *root) {
if(root==NULL) {
return 0;
}
int left = balanced(root->left);
if(left==-1) return -1;
int right = balanced(root->right);
if(right==-1) return -1;
if(abs(left-right) > 1) return -1;
return max(left, right)+1;
}
bool isBalanced(TreeNode *root) {
if(root == NULL) return true;
int h = balanced(root);
return h!=-1;
}
}
相关文章推荐
- 玩具工厂
- JDK字符串查找算法
- iOS集合视图学习笔记
- is not allowed to connect to this MySQL server解决办法
- babel 编译后 this 变成了 undefined
- 轻松把玩HttpClient之封装HttpClient工具类(七),新增验证码识别功能
- android学习路线
- 逻辑炸弹程序
- Gensim Word2vec简介
- 进程调度算法
- 【BZOJ3673】&&【BZOJ3674】: 可持久化并查集 by zky 可持久化线段树
- R语言中的数学计算(转载)
- struts拓展restful
- 热启动和冷启动
- java-CompletionService
- struts拓展restful
- 【BZOJ3207】花神的嘲讽计划I 可持久化线段树/莫队
- 欢迎使用CSDN-markdown编辑器
- Java学习之路(第七天)
- 清代宗族义庄的发展——以苏南地区为考察中心