Skip to content

Commit f54ec65

Browse files
committed
feat: solve new question
1 parent 95a8ea4 commit f54ec65

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

balanced-binary-tree/main.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
9+
root = [3,9,20,null,null,15,7]
10+
11+
3
12+
/ \
13+
9 20
14+
/ \
15+
15 7
16+
17+
*/
18+
/**
19+
* @param {TreeNode} root
20+
* @return {boolean}
21+
*/
22+
var isBalanced = function(root) {
23+
24+
function dfs(root) {
25+
if (root == null) return [true, 0];
26+
27+
let left = dfs(root.left);
28+
let right = dfs(root.right);
29+
30+
let balanced = (left[0] && right[0] && Math.abs(left[1] - right[1]) <= 1);
31+
return [balanced, 1 + Math.max(left[1], right[1])];
32+
}
33+
34+
return dfs(root)[0];
35+
};

0 commit comments

Comments
 (0)