Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 30c080b

Browse files
committedApr 5, 2018
Fix binary tree node.
1 parent d19149d commit 30c080b

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed
 

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ export default class BinaryTreeNode {
2626
return Math.max(this.leftHeight, this.rightHeight);
2727
}
2828

29+
get balanceFactor() {
30+
return this.leftHeight - this.rightHeight;
31+
}
32+
2933
setLeft(node) {
3034
this.left = node;
3135
this.left.parent = this;

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,15 @@ describe('BinaryTreeNode', () => {
115115
const grandGrandLeft = new BinaryTreeNode(7);
116116

117117
expect(root.height).toBe(0);
118+
expect(root.balanceFactor).toBe(0);
118119

119120
root
120121
.setLeft(left)
121122
.setRight(right);
122123

123124
expect(root.height).toBe(1);
124125
expect(left.height).toBe(0);
126+
expect(root.balanceFactor).toBe(0);
125127

126128
left
127129
.setLeft(grandLeft)
@@ -131,6 +133,7 @@ describe('BinaryTreeNode', () => {
131133
expect(left.height).toBe(1);
132134
expect(grandLeft.height).toBe(0);
133135
expect(grandRight.height).toBe(0);
136+
expect(root.balanceFactor).toBe(1);
134137

135138
grandLeft.setLeft(grandGrandLeft);
136139

@@ -139,6 +142,7 @@ describe('BinaryTreeNode', () => {
139142
expect(grandLeft.height).toBe(1);
140143
expect(grandRight.height).toBe(0);
141144
expect(grandGrandLeft.height).toBe(0);
145+
expect(root.balanceFactor).toBe(2);
142146
});
143147

144148
it('should calculate node height for right nodes as well', () => {
@@ -149,5 +153,6 @@ describe('BinaryTreeNode', () => {
149153

150154
expect(root.height).toBe(1);
151155
expect(right.height).toBe(0);
156+
expect(root.balanceFactor).toBe(-1);
152157
});
153158
});

0 commit comments

Comments
 (0)