当前位置:网站首页>[leetcode] 93 balanced binary tree
[leetcode] 93 balanced binary tree
2020-11-10 01:15:00 【JaneRoad】
subject :


Their thinking :
Bottom up recursion
Similar to post order traversal , For the node currently traversed , First, recursively judge whether the left and right subtrees are balanced , Then judge whether the subtree with the current node as the root is balanced . If a subtree is balanced , Then return to its height ( The height must be a nonnegative integer ), Otherwise return to -1−1. If there is a subtree imbalance , Then the whole binary tree must be unbalanced .
Code :
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
版权声明
本文为[JaneRoad]所创,转载请带上原文链接,感谢
边栏推荐
- 关于centos启动报错:Failed to start Crash recovery kernel arming的解决方案
- 树莓派鼓捣记 - 设置 wifi
- js label语法跳出多重循环
- z-index属性详解
- lodash.js Source code flatten
- Can't find other people's problem to solve
- Python cookbook 3rd note (2.1): using multiple qualifiers to split strings
- Python提示AttributeError 或者DeprecationWarning: This module was deprecated解决方法
- Usage of [:] and [::] in Python
- 假如需要一百万个对象
猜你喜欢

C++ exception implementation mechanism

接缝雕刻算法:一种看似不可能的图像大小调整方法

Using tail as time series to identify whales

Visit 2020 PG Technology Conference

Coding style: SSM environment in MVC mode, code hierarchical management

Difficulties in heterogeneous middleware implementation of Bifrost site management (1)

SQL intercepts the data before and after the '.'

编码风格:Mvc模式下SSM环境,代码分层管理

iNeuOS工业互联平台,WEB组态(iNeuView)增加工程视图导入、导出功能,及优化和修复,发布:v3.2.1版本

The length of the last word in leetcode
随机推荐
What is the architecture of a live broadcast system worth more than $1 billion?
JS solves the problem of automatic pagination in browser printing
Mongodb index management of distributed document storage database
The solution of polar experience insensitive verification
asp.net core中使用Serilog以及自定义Enricher
Exhibition cloud technology interpretation | in the face of emergencies, how does app do a good job in crash analysis and performance monitoring?
Incomplete Polyfill of proxy
proxy 的不完整polyfill
lodash.js源码-flatten
How SSL certificate and public IP address affect SEO
Notes on Python cookbook 3rd (2.2): String start or end match
YouTube subscription: solve the problem of incomplete height display of YouTube subscription button in pop-up window
【CentOS7操作系统安全加固系列】第(2)篇
接缝雕刻算法:一种看似不可能的图像大小调整方法
Algorithm template arrangement (1)
Important components of Apache Hadoop
一幅图像能顶16x16字!——用于大规模图像缩放识别的变压器(对ICLR 2021年论文的简要回顾)
JMeter的简单使用
lodash.js Source code flatten
C++异常实现机制