Example #1
0
		it('can walk a tree in order', function() {
			const tree = new BinaryTree(numericalCompare)

			tree.insert(3)
			tree.insert(4)
			tree.insert(1)
			tree.insert(2)

			const result: any[] = []
			walkInOrder(tree, tree.root, n => result.push(n.key))

			expect(result).toEqual([1, 2, 3, 4])
		})
Example #2
0
		it('tree height is always max log(n) * 2 and has same black node count', function() {
			const numbers = times(Math.random, 100).map(n => Math.floor(n * 100))

			const tree = new RBTree(numericalCompare)

			let count = 0

			for (const n of numbers) {
				tree.insert(n)
				count++

				let minBlackCount = 0
				const minNode = min(tree, tree.root)
				walkToRoot(tree, minNode, n => {
					if (!(n as RBNode<number>).red) {
						minBlackCount++
					}
				})

				walkInOrder(tree, tree.root, n => {
					if (n.left === tree.nil && n.right === tree.nil) {
						let height = 0
						let blackCount = 0
						walkToRoot(tree, n, n => {
							height++
							if (!(n as RBNode<number>).red) {
								blackCount++
							}
						})

						expect(blackCount).toBe(minBlackCount)
						expect(height).toBeLessThan(
							Math.floor(Math.log2(count + 1) * 2 + 1),
						)
					}
				})
			}

			expect(count === numbers.length && count === tree.size()).toBe(true)

			const shuffled = shuffle(numbers)

			for (const n of shuffled) {
				tree.remove(n)
				count--

				let minBlackCount = 0
				const minNode = min(tree, tree.root)
				walkToRoot(tree, minNode, n => {
					if (!(n as RBNode<number>).red) {
						minBlackCount++
					}
				})

				walkInOrder(tree, tree.root, n => {
					if (n.left === tree.nil && n.right === tree.nil) {
						let height = 0
						let blackCount = 0
						walkToRoot(tree, n, n => {
							height++
							if (!(n as RBNode<number>).red) {
								blackCount++
							}
						})

						expect(blackCount).toBe(minBlackCount)
						expect(height).toBeLessThan(
							Math.floor(Math.log2(count + 1) * 2 + 1),
						)
					}
				})
			}
		})