Skip to content

Commit f4597c2

Browse files
committed
Added 110. Balanced Binary Tree
1 parent 84a02fa commit f4597c2

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
/**
10+
* @param {TreeNode} root
11+
* @return {boolean}
12+
*/
13+
var isBalanced = function (root) {
14+
if (!root) return true
15+
const left = findHeight(root.left)
16+
const right = findHeight(root.right)
17+
return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right)
18+
};
19+
20+
function findHeight(node) {
21+
if (node == null) return 0;
22+
return 1 + Math.max(this.findHeight(node.left), this.findHeight(node.right));
23+
}
24+
25+
// Runtime: 78 ms, faster than 90.43% of JavaScript online submissions for Balanced Binary Tree.
26+
// Memory Usage: 47.1 MB, less than 32.41% of JavaScript online submissions for Balanced Binary Tree.

0 commit comments

Comments
 (0)