Fix binary tree node.

This commit is contained in:
Oleksii Trekhleb 2018-04-06 07:01:16 +03:00
parent 30c080ba02
commit 9eefd13615
2 changed files with 24 additions and 2 deletions

View File

@ -32,13 +32,17 @@ export default class BinaryTreeNode {
setLeft(node) { setLeft(node) {
this.left = node; this.left = node;
if (node) {
this.left.parent = this; this.left.parent = this;
}
return this; return this;
} }
setRight(node) { setRight(node) {
this.right = node; this.right = node;
if (node) {
this.right.parent = this; this.right.parent = this;
}
return this; return this;
} }

View File

@ -155,4 +155,22 @@ describe('BinaryTreeNode', () => {
expect(right.height).toBe(0); expect(right.height).toBe(0);
expect(root.balanceFactor).toBe(-1); expect(root.balanceFactor).toBe(-1);
}); });
it('should set null for left and right node', () => {
const root = new BinaryTreeNode(2);
const left = new BinaryTreeNode(1);
const right = new BinaryTreeNode(3);
root.setLeft(left);
root.setRight(right);
expect(root.left.value).toBe(1);
expect(root.right.value).toBe(3);
root.setLeft(null);
root.setRight(null);
expect(root.left).toBeNull();
expect(root.right).toBeNull();
});
}); });