We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 6ecbf13 commit c2e4972Copy full SHA for c2e4972
algorithms/balanced-binary-tree.js
@@ -7,7 +7,6 @@
7
* }
8
*/
9
/**
10
- * 平衡二叉树
11
* @param {TreeNode} root
12
* @return {boolean}
13
@@ -16,27 +15,17 @@ var isBalanced = function (root) {
16
15
if (!node) return 0;
17
const leftHeight = helper(node.left);
18
const rightHeight = helper(node.right);
+ // 左子树 右子树 高度差的绝对值
19
const abs = Math.abs(leftHeight - rightHeight);
20
-
+ // 后序遍历(先访问左右子树,然后才访问父节点)
21
if (leftHeight >= 0 && rightHeight >= 0 && abs <= 1) {
22
+ // 根节点高度
23
return Math.max(leftHeight, rightHeight) + 1;
24
} else {
- -1;
25
+ // 表示不是平衡二叉树了
26
+ return -1;
27
}
28
29
30
return helper(root) >= 0;
31
};
-/*
32
- * 1
33
- * / \
34
- * 2 2
35
36
- * 3 3
37
38
- * 4 4
39
- *
40
- * 从基准情形开始分析,即最左边节点(值为4)开始,类似后序遍历,
41
- * 计算根节点的左右子树的高度差,如果不符合条件,则返回-1,即该树不是平衡二叉树。
42
- */
0 commit comments