题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
package com.hhdd.数据结构.树;
/**
* @Author huanghedidi
* @Date 2022/8/24 23:35
*/
public class 判断是否平衡二叉树 {
public boolean IsBalanced_Solution(TreeNode root) {
int res = treeDepth(root);
return res == -1 ? false : true;
}
public int treeDepth(TreeNode root) {
if (root == null) {
return 0;
}
/**
* 求左子树深度
*/
int l = treeDepth(root.left);
// 返回 -1 则说明左子树已不是平衡二叉
if (l == -1) {
return -1;
}
int r = treeDepth(root.right);
if (r == -1) {
return -1;
}
if (Math.abs(l - r) > 1) {
return -1;
}
return Math.max(l, r) + 1;
}
}
查看19道真题和解析