当前位置:网站首页>LeetCode-110-平衡二叉树
LeetCode-110-平衡二叉树
2022-06-11 21:23:00 【z754916067】
题目

思路
- 思路是对二叉树做先序遍历,从底至顶返回子树最大高度,若判定某子树不是平衡树则 “剪枝” ,直接向上返回。
- 如果左右高度差≥2 :则返回 -1,代表 此子树不是平衡树,然后接着向上返回 只有全都是平衡树 才会返回非-1的值
代码
public boolean isBalanced(TreeNode root) {
return recur(root) != -1;
}
//思路是对二叉树做先序遍历,从底至顶返回子树最大高度,若判定某子树不是平衡树则 “剪枝” ,直接向上返回。
private int recur(TreeNode root) {
//空指针返回0
if (root == null) return 0;
int left = recur(root.left);
if(left == -1) return -1;
int right = recur(root.right);
if(right == -1) return -1;
//如果当前节点的左右子树的高度差<2 说明在当前节点算是平衡子树
//返回以节点root为根节点的子树的最大高度,即节点 root 的左右子树中最大高度加 1
//但如果左右高度差≥2 :则返回 -1,代表 此子树不是平衡树,然后接着向上返回 只有全都是平衡树 才会返回非-1的值
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
}
边栏推荐
- 关于gorm的preload方法笔记说明
- How to manually drag nodes in the Obsidian relationship graph
- 【生活思考】文字与语音
- Stream Chinese sorting
- Add personal statement for go file in file template in Golan
- 常用文件函数
- Work assessment of spectral analysis of Jilin University in March of the 22nd spring -00079
- JS performs non empty judgment on various data types of the returned data.
- What are striplines and microstrip lines? Reference planes and transmission lines
- JUnit tests multithreaded code, and the sub thread does not run
猜你喜欢

【博弈论-完全信息静态博弈】 战略式博弈

LabVIEW controls Arduino to realize ultrasonic ranging (advanced chapter-5)

Pyqt5 technical part - set the default value of qcombobox drop-down box and get the current selection of the drop-down box

SQL的语法

JMeter load test finds the maximum number of concurrent users (including step analysis)

go语言的goto语句

Test plans and test cases

Codeforces Round #744 (Div. 3) 解题报告

JVM method area

Database daily question --- day 9: salesperson
随机推荐
How to manually drag nodes in the Obsidian relationship graph
table_ Display status
JVM方法区
RANSAC extraction plane (matlab built-in function)
[Game Theory - introduction]
JVM之对象创建过程
A man always becomes a man and a man always arrives (progress, harvest, growth, self-confidence)
八、BOM - 章节课后练习题及答案
Application business layer modification
数据库每日一题---第9天:销售员
一个Golang的私有库设置问题
【生活思考】文字与语音
JVM method area
解决 img 5px 间距的问题
JS monitor scrolling touch bottom load more_ Browser scrolls to the bottom to load more
Tensorflow 2. X Getting Started tutorial
如何将SAP API Hub 上提供的工作流导入到 SAP BTP 上
The difference between VaR and let_ The difference between let and VaR
Field queryIndexFieldnameService in xxxImpl required a single bean, but 19 were found:
可综合RTL代码设计方法和注意事项