当前位置:网站首页>【LeetCode】 93 平衡二叉树
【LeetCode】 93 平衡二叉树
2020-11-10 01:15:00 【JaneRoad】
题目:
解题思路:
自底向上的递归
类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),否则返回 -1−1。如果存在一棵子树不平衡,则整个二叉树一定不平衡。
代码:
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]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4248053/blog/4710406
边栏推荐
- Fear of reconstruction? I'm too late to tell you how to refactor. Now I'm here
- SRM系统是什么系统?SRM供应商管理系统功能
- 完美日记母公司逸仙电商招股书:重营销、轻研发,前三季度亏11亿
- Gets the property value of a column in the list collection object
- lodash.js源码-flatten
- 《Python Cookbook 3rd》笔记(2.1):使用多个界定符分割字符串
- Common concepts and points for attention of CUDA
- Prometheus installation configuration
- The number of more than half of the array is printed by the sword
- Algorithm template arrangement (1)
猜你喜欢
痞子衡嵌入式:RT-UFL - 一个适用全平台i.MXRT的超级下载算法设计
SQL intercepts the data before and after the '.'
C++异常实现机制
会展云技术解读 | 面对突发事故,APP 如何做好崩溃分析与性能监控?
Usage of [:] and [::] in Python
Prometheus installation configuration
leetcode之最后一个单词的长度
Centos7 operating system security hardening series (2)
The length of the last word in leetcode
What is the SRM system? SRM supplier management system functions
随机推荐
Assign the corresponding key and value in the map to the object
Brief analysis of LinkedList source code
Seam engraving algorithm: a seemingly impossible image size adjustment method
Prometheus安装配置
实验2
Coding style: SSM environment in MVC mode, code hierarchical management
CUDA_ Global memory and access optimization
js解决浏览器打印自动分页的问题
Python提示AttributeError 或者DeprecationWarning: This module was deprecated解决方法
《Python Cookbook 3rd》笔记(2.1):使用多个界定符分割字符串
Usage of [:] and [::] in Python
害怕重构?都怪我太晚和你介绍该如何重构,现在我来了
Assign the corresponding key and value in the map to the object
爱康国宾怒斥国信证券报告失实,已发律师函
消防知识线上答题活动小程序复盘
C++异常实现机制
Using tail as time series to identify whales
Functional guide for temporary users and novices of PL / SQL developer
Unity使用transform.Rotate进行三维旋转角度出现偏差
接缝雕刻算法:一种看似不可能的图像大小调整方法