Skip to content

Commit e3caee6

Browse files
committed
Add Balanced Binary Tree TS Solution
1 parent d5c95dc commit e3caee6

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function isBalanced(root: TreeNode | null): boolean {
2+
if (!root) {
3+
return true;
4+
}
5+
console.log(balance(root));
6+
return balance(root) !== -1
7+
8+
//自底至顶 后续遍历
9+
function balance(root: TreeNode | null): number {
10+
if (!root) {
11+
return 0;
12+
}
13+
let leftDepth = balance(root.left);
14+
if (leftDepth == -1) return -1;
15+
let rightDepth = balance(root.right);
16+
if (rightDepth == -1) return -1;
17+
if (Math.abs(leftDepth - rightDepth) > 1) return -1;
18+
return 1 + Math.max(leftDepth, rightDepth);
19+
}
20+
};

0 commit comments

Comments
 (0)