|
| 1 | +import { Tree } from '../BinarySearchTree.js' |
| 2 | + |
| 3 | +describe('Binary Search Tree', () => { |
| 4 | + let tree |
| 5 | + |
| 6 | + beforeEach(() => { |
| 7 | + tree = new Tree() |
| 8 | + }) |
| 9 | + |
| 10 | + test('should add values to the tree', () => { |
| 11 | + tree.addValue(10) |
| 12 | + tree.addValue(5) |
| 13 | + tree.addValue(15) |
| 14 | + |
| 15 | + expect(tree.search(10)).toBe(10) |
| 16 | + expect(tree.search(5)).toBe(5) |
| 17 | + expect(tree.search(15)).toBe(15) |
| 18 | + }) |
| 19 | + |
| 20 | + test('should perform in-order traversal', () => { |
| 21 | + const values = [] |
| 22 | + const output = (val) => values.push(val) |
| 23 | + |
| 24 | + tree.addValue(10) |
| 25 | + tree.addValue(5) |
| 26 | + tree.addValue(15) |
| 27 | + tree.addValue(3) |
| 28 | + tree.addValue(8) |
| 29 | + |
| 30 | + tree.traverse(output) |
| 31 | + expect(values).toEqual([3, 5, 8, 10, 15]) |
| 32 | + }) |
| 33 | + |
| 34 | + test('should remove leaf nodes correctly', () => { |
| 35 | + tree.addValue(10) |
| 36 | + tree.addValue(5) |
| 37 | + tree.addValue(15) |
| 38 | + |
| 39 | + tree.removeValue(5) |
| 40 | + expect(tree.search(5)).toBeNull() |
| 41 | + }) |
| 42 | + |
| 43 | + test('should remove nodes with one child correctly', () => { |
| 44 | + tree.addValue(10) |
| 45 | + tree.addValue(5) |
| 46 | + tree.addValue(15) |
| 47 | + tree.addValue(12) |
| 48 | + |
| 49 | + tree.removeValue(15) |
| 50 | + expect(tree.search(15)).toBeNull() |
| 51 | + expect(tree.search(12)).toBe(12) |
| 52 | + }) |
| 53 | + |
| 54 | + test('should remove nodes with two children correctly', () => { |
| 55 | + tree.addValue(10) |
| 56 | + tree.addValue(5) |
| 57 | + tree.addValue(15) |
| 58 | + tree.addValue(12) |
| 59 | + tree.addValue(18) |
| 60 | + |
| 61 | + tree.removeValue(15) |
| 62 | + expect(tree.search(15)).toBeNull() |
| 63 | + expect(tree.search(12)).toBe(12) |
| 64 | + expect(tree.search(18)).toBe(18) |
| 65 | + }) |
| 66 | + |
| 67 | + test('should return null for non-existent values', () => { |
| 68 | + tree.addValue(10) |
| 69 | + tree.addValue(5) |
| 70 | + tree.addValue(15) |
| 71 | + |
| 72 | + expect(tree.search(20)).toBeNull() |
| 73 | + expect(tree.search(0)).toBeNull() |
| 74 | + }) |
| 75 | + |
| 76 | + test('should handle removal of root node correctly', () => { |
| 77 | + tree.addValue(10) |
| 78 | + tree.addValue(5) |
| 79 | + tree.addValue(15) |
| 80 | + |
| 81 | + tree.removeValue(10) |
| 82 | + expect(tree.search(10)).toBeNull() |
| 83 | + }) |
| 84 | + |
| 85 | + test('should handle empty tree gracefully', () => { |
| 86 | + expect(tree.search(10)).toBeNull() |
| 87 | + tree.removeValue(10) // Should not throw |
| 88 | + }) |
| 89 | +}) |
0 commit comments