Skip to content

Commit c2e4972

Browse files
committed
Update 10. 平衡二叉树
1 parent 6ecbf13 commit c2e4972

File tree

1 file changed

+5
-16
lines changed

1 file changed

+5
-16
lines changed

algorithms/balanced-binary-tree.js

+5-16
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
* }
88
*/
99
/**
10-
* 平衡二叉树
1110
* @param {TreeNode} root
1211
* @return {boolean}
1312
*/
@@ -16,27 +15,17 @@ var isBalanced = function (root) {
1615
if (!node) return 0;
1716
const leftHeight = helper(node.left);
1817
const rightHeight = helper(node.right);
18+
// 左子树 右子树 高度差的绝对值
1919
const abs = Math.abs(leftHeight - rightHeight);
20-
20+
// 后序遍历(先访问左右子树,然后才访问父节点)
2121
if (leftHeight >= 0 && rightHeight >= 0 && abs <= 1) {
22+
// 根节点高度
2223
return Math.max(leftHeight, rightHeight) + 1;
2324
} else {
24-
-1;
25+
// 表示不是平衡二叉树了
26+
return -1;
2527
}
2628
}
2729

2830
return helper(root) >= 0;
2931
};
30-
31-
/*
32-
* 1
33-
* / \
34-
* 2 2
35-
* / \
36-
* 3 3
37-
* / \
38-
* 4 4
39-
*
40-
* 从基准情形开始分析,即最左边节点(值为4)开始,类似后序遍历,
41-
* 计算根节点的左右子树的高度差,如果不符合条件,则返回-1,即该树不是平衡二叉树。
42-
*/

0 commit comments

Comments
 (0)