题目:给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
leetcode原题链接
思路:每一步都判断他是否是高度平衡的,如果不是返回-1,如果是树的深度。
function isBalanced(root) {
return height(root) >= 0;
function height(root) {
if (!root) {
return 0;
}
const leftDeep = height(root.left);
const rightDeep = height(root.right);
if (leftDeep === -1 || rightDeep === -1 || Math.abs(leftDeep - rightDeep) > 1) {
return -1;
} else {
return Math.max(leftDeep, rightDeep) + 1;
}
}
}
每天两道简单题,什么时候才能变强啊啊