Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
- [Construct Binary Tree From Preorder and Inorder Traversal](src/tree/construct-binary-tree-from-preorder-and-inorder-traversal.js)
- [Construct Binary Tree From Postorder and Inorder Traversal](src/tree/construct-binary-tree-from-inorder-and-postorder-traversal.js)
- [Convert Sorted Array to Binary Search Tree](src/tree/convert-sorted-array-to-binary-search-tree.js)
- [Balanced Binary Tree](src/tree/balanced-binary-tree.js)

### Dynamic Programming

Expand Down
24 changes: 24 additions & 0 deletions src/tree/__tests__/balanced-binary-tree-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { assert } from 'chai';
import { deserializeTree } from 'utils/tree-util';
import isBalanced from '../balanced-binary-tree';

describe('Balanced Binary Tree', () => {
const testCases = [
['', true],
['1', true],
['1,2', true],
['1,2,null,3', false],
['1,null,2,null,3', false],
['1,2,null,3,null,4', false],
['1,null,2,null,3,null,4', false],
];

testCases.map((testCase, index) => {
it(`should validate tree ${testCase[0]} if it's balanced`, () => {
const root = deserializeTree(testCase[0]);
const actual = isBalanced(root);
const expected = testCase[1];
assert.equal(actual, expected);
});
});
});
34 changes: 34 additions & 0 deletions src/tree/balanced-binary-tree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Given a binary tree, determine if it is height-balanced.
*
* For this problem, a height-balanced binary tree is defined as a binary tree
* in which the depth of the two subtrees of every node never differ by more than 1.
*/

const isBalanced = root => {
const getHeight = root => {
if (!root) {
return 0;
}

const leftHeight = getHeight(root.left);
if (leftHeight < 0) {
return -1;
}

const rightHeight = getHeight(root.right);
if (rightHeight < 0) {
return -1;
}

if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}

return 1 + Math.max(leftHeight, rightHeight);
};

return getHeight(root) >= 0;
};

export default isBalanced;