Skip to content

Commit 9eefd13

Browse files
committedApr 6, 2018
Fix binary tree node.
1 parent 30c080b commit 9eefd13

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed
 

‎src/data-structures/tree/BinaryTreeNode.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,17 @@ export default class BinaryTreeNode {
3232

3333
setLeft(node) {
3434
this.left = node;
35-
this.left.parent = this;
35+
if (node) {
36+
this.left.parent = this;
37+
}
3638
return this;
3739
}
3840

3941
setRight(node) {
4042
this.right = node;
41-
this.right.parent = this;
43+
if (node) {
44+
this.right.parent = this;
45+
}
4246
return this;
4347
}
4448

‎src/data-structures/tree/__test__/BinaryTreeNode.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,4 +155,22 @@ describe('BinaryTreeNode', () => {
155155
expect(right.height).toBe(0);
156156
expect(root.balanceFactor).toBe(-1);
157157
});
158+
159+
it('should set null for left and right node', () => {
160+
const root = new BinaryTreeNode(2);
161+
const left = new BinaryTreeNode(1);
162+
const right = new BinaryTreeNode(3);
163+
164+
root.setLeft(left);
165+
root.setRight(right);
166+
167+
expect(root.left.value).toBe(1);
168+
expect(root.right.value).toBe(3);
169+
170+
root.setLeft(null);
171+
root.setRight(null);
172+
173+
expect(root.left).toBeNull();
174+
expect(root.right).toBeNull();
175+
});
158176
});

0 commit comments

Comments
 (0)
Please sign in to comment.