Skip to content

Commit e47dbec

Browse files
committed
Add balanced binary tree JS LC medium
1 parent 37ccfb4 commit e47dbec

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
https://leetcode.com/problems/balanced-binary-tree
3+
4+
Given a binary tree, return true if it is height-balanced and false otherwise.
5+
6+
A height-balanced binary tree is defined as a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
7+
8+
Example 1:
9+
Input: root = [1,2,3,null,null,4]
10+
Output: true
11+
12+
Example 2:
13+
Input: root = [1,2,3,null,null,4,null,5]
14+
Output: false
15+
16+
Example 3:
17+
Input: root = []\
18+
Output: true
19+
20+
Constraints:
21+
The number of nodes in the tree is in the range [0, 1000].
22+
-1000 <= Node.val <= 1000
23+
*/
24+
25+
class TreeNode {
26+
constructor(val = 0, left = null, right = null) {
27+
this.val = val;
28+
this.left = left;
29+
this.right = right;
30+
}
31+
}
32+
33+
function isBalanced(root) {
34+
function traverse(node) {
35+
if (!node) {
36+
return [true, 0];
37+
}
38+
39+
const left = traverse(node.left);
40+
const right = traverse(node.right);
41+
const balanced =
42+
left[0] && right[0] && Math.abs(left[1] - right[1]) <= 1;
43+
44+
return [balanced, 1 + Math.max(left[1], right[1])];
45+
}
46+
47+
return traverse(root)[0];
48+
}
49+
50+
module.exports = { isBalanced, TreeNode };
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const { isBalanced, TreeNode } = require("./balancedBinaryTree");
2+
3+
describe("isBalanced", () => {
4+
it("should return true if the tree is balanced", () => {
5+
const root = new TreeNode(1);
6+
root.left = new TreeNode(2);
7+
root.right = new TreeNode(3);
8+
expect(isBalanced(root)).toBe(true);
9+
});
10+
11+
it("should return false if the tree is not balanced", () => {
12+
const root = new TreeNode(1);
13+
root.left = new TreeNode(2);
14+
root.right = new TreeNode(3);
15+
root.left.left = new TreeNode(4);
16+
root.left.left.left = new TreeNode(5);
17+
expect(isBalanced(root)).toBe(false);
18+
});
19+
20+
it("should return true if the tree is empty", () => {
21+
const root = null;
22+
expect(isBalanced(root)).toBe(true);
23+
});
24+
});

0 commit comments

Comments
 (0)