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 857edbf

Browse files
committedApr 4, 2018
Add possibility for tree nodes to have height.
1 parent d98c52c commit 857edbf

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
 

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,17 @@ export default class BinaryTreeNode {
66
this.value = value;
77
}
88

9+
get height() {
10+
if (!this.left && !this.left) {
11+
return 0;
12+
}
13+
14+
const leftHeight = this.left ? this.left.height : 0;
15+
const rightHeight = this.right ? this.right.height : 0;
16+
17+
return Math.max(leftHeight, rightHeight) + 1;
18+
}
19+
920
setLeft(node) {
1021
this.left = node;
1122
this.left.parent = this;

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,44 @@ describe('BinaryTreeNode', () => {
100100
expect(rootNode.replaceChild(rootNode.right, replacementNode)).toBeTruthy();
101101
expect(rootNode.traverseInOrder()).toEqual([1, 2, 5]);
102102

103+
expect(rootNode.replaceChild(rootNode.left, replacementNode)).toBeTruthy();
104+
expect(rootNode.traverseInOrder()).toEqual([5, 2, 5]);
105+
103106
expect(rootNode.replaceChild(new BinaryTreeNode(), new BinaryTreeNode())).toBeFalsy();
104107
});
108+
109+
it('should calculate node height', () => {
110+
const root = new BinaryTreeNode(1);
111+
const left = new BinaryTreeNode(3);
112+
const right = new BinaryTreeNode(2);
113+
const grandLeft = new BinaryTreeNode(5);
114+
const grandRight = new BinaryTreeNode(6);
115+
const grandGrandLeft = new BinaryTreeNode(7);
116+
117+
expect(root.height).toBe(0);
118+
119+
root
120+
.setLeft(left)
121+
.setRight(right);
122+
123+
expect(root.height).toBe(1);
124+
expect(left.height).toBe(0);
125+
126+
left
127+
.setLeft(grandLeft)
128+
.setRight(grandRight);
129+
130+
expect(root.height).toBe(2);
131+
expect(left.height).toBe(1);
132+
expect(grandLeft.height).toBe(0);
133+
expect(grandRight.height).toBe(0);
134+
135+
grandLeft.setLeft(grandGrandLeft);
136+
137+
expect(root.height).toBe(3);
138+
expect(left.height).toBe(2);
139+
expect(grandLeft.height).toBe(1);
140+
expect(grandRight.height).toBe(0);
141+
expect(grandGrandLeft.height).toBe(0);
142+
});
105143
});

0 commit comments

Comments
 (0)
Please sign in to comment.