2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_110.java 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2021-01-14 15:01 . 二叉树
package com.hit.basmath.learn.binary_search_tree;
import com.hit.common.TreeNode;
/**
* 110. 平衡二叉树
* 给定一个二叉树,判断它是否是高度平衡的二叉树。
* <p>
* 本题中,一棵高度平衡二叉树定义为:
* <p>
* 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
* <p>
* 示例 1:
* <p>
* 输入:root = [3,9,20,null,null,15,7]
* 输出:true
* <p>
* 示例 2:
* <p>
* 输入:root = [1,2,2,3,3,null,null,4,4]
* 输出:false
* <p>
* 示例 3:
* <p>
* 输入:root = []
* 输出:true
* <p>
* 提示:
* <p>
* 树中的节点数在范围 [0, 5000] 内
* -10^4 <= Node.val <= 10^4
*/
public class _110 {
private boolean result = true;
public boolean isBalanced(TreeNode root) {
maxDepth(root);
return result;
}
private int maxDepth(TreeNode root) {
if (root == null) return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
if (Math.abs(leftDepth - rightDepth) > 1) result = false;
return 1 + Math.max(leftDepth, rightDepth);
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助