|
| 1 | +class Node { |
| 2 | + constructor(value) { |
| 3 | + this.value = value; |
| 4 | + this.left = null; |
| 5 | + this.right = null; |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +class BinarySearchTree { |
| 10 | + constructor() { |
| 11 | + this.root = null; |
| 12 | + } |
| 13 | + insert(value) { |
| 14 | + var newNode = new Node(value); |
| 15 | + if (this.root === null) { |
| 16 | + this.root = newNode; |
| 17 | + return this; |
| 18 | + } |
| 19 | + var current = this.root; |
| 20 | + while (true) { |
| 21 | + if (value === current.value) return undefined; |
| 22 | + if (value < current.value) { |
| 23 | + if (current.left === null) { |
| 24 | + current.left = newNode; |
| 25 | + return this; |
| 26 | + } |
| 27 | + current = current.left; |
| 28 | + } else { |
| 29 | + if (current.right === null) { |
| 30 | + current.right = newNode; |
| 31 | + return this; |
| 32 | + } |
| 33 | + current = current.right; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + find(value) { |
| 38 | + if (this.root === null) return false; |
| 39 | + var current = this.root, |
| 40 | + found = false; |
| 41 | + while (current && !found) { |
| 42 | + if (value < current.value) { |
| 43 | + current = current.left; |
| 44 | + } else if (value > current.value) { |
| 45 | + current = current.right; |
| 46 | + } else { |
| 47 | + found = true; |
| 48 | + } |
| 49 | + } |
| 50 | + if (!found) return undefined; |
| 51 | + return current; |
| 52 | + } |
| 53 | + contains(value) { |
| 54 | + if (this.root === null) return false; |
| 55 | + var current = this.root, |
| 56 | + found = false; |
| 57 | + while (current && !found) { |
| 58 | + if (value < current.value) current = current.left; |
| 59 | + else if (value > current.value) current = current.right; |
| 60 | + else return true; |
| 61 | + } |
| 62 | + return false; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// 10 |
| 67 | +// 5 13 |
| 68 | +// 2 7 11 16 |
| 69 | + |
| 70 | +var tree = new BinarySearchTree(); |
| 71 | +tree.insert(10); |
| 72 | +tree.insert(5); |
| 73 | +tree.insert(13); |
| 74 | +tree.insert(11); |
| 75 | +tree.insert(2); |
| 76 | +tree.insert(16); |
| 77 | +tree.insert(7); |
| 78 | + |
| 79 | +console.log(tree.find(13)); |
| 80 | +console.log(tree.find(19)); |
| 81 | + |
| 82 | +console.log(tree.contains(2)); |
| 83 | +console.log(tree.contains(534)); |
0 commit comments