为什么记录?
主要通过文章来更有条理梳理看的题解和自己的思路,每天刷一点,算法题应该是有套路和分类刷的情况,就跟考试刷题的感觉差不多...就刷刷 easy 吧~
平衡二叉树定义
- 首先它是二叉树
- 它任意节点的
左右子树的深度之差不能超过 1 - 就判定它是平衡二叉树
关键点
- 需要获取节点的左右子树的深度(这个应该是树类算法必备)
// 深度模式获取
let result = true;
const { max } = Math;
function dfs(root) {
// 遍历到最后末节点
if (root === null) return 0;
// 分别遍历 leftNode and rightNode
const leftDepth = dfs(root.left);
const rightDepth = dfs(root.right);
// 这个时候判断他们的成立条件...
// slot: 条件是`左右子树`的深度之差`不能超过 1`
// 每次获取子树高度最大的,然后 +1 存入递归栈结果
return max( leftDepth, rightDepth ) + 1;
}
- 判定条件
// 在上面 slot 递归值出队的时候,就可以拿到提前对每一个遍历的子树做判定了
const leftDepth = dfs(root.left);
const rightDepth = dfs(root.right);
if (abs( leftDepth - rightDepth ) > 1) {
result = false; // 只要有一个子树不符合了,就判定失败
}
return max( leftDepth, rightDepth ) + 1;
- 全部代码
const { abs, max } = Math;
function isBalanced(root) {
if (root === null) return true;
let result = true;
function dfs(root) {
// 遍历到最后末节点
if (root === null) return 0;
// 分别遍历 leftNode and rightNode
const leftDepth = dfs(root.left);
const rightDepth = dfs(root.right);
// 这个时候判断他们的成立条件...
// slot: 条件是`左右子树`的深度之差`不能超过 1`
if (abs( leftDepth - rightDepth ) > 1) {
// 只要有一个子树不符合了,就判定失败
result = false;
}
// 每次获取子树高度最大的,然后 +1 存入递归栈结果
return max( leftDepth, rightDepth ) + 1;
}
dfs(root);
return result;
}