1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| function BinarySearchTree() { let Node = function(key) { this.key = key; this.left = null; this.right = null; } let root = null; const insertNode = (node, newNode) => { if (newNode.key < node.key) { if (node.left === null) { node.left = newNode; } else { insertNode(node.left, newNode); } } else { if (node.right === null) { node.right = newNode; } else { insertNode(node.right, newNode); } } } this.insert = key => { const newNode = new Node(key); if (root === null) { root = newNode; } else { insertNode(root, newNode); } } const searchNode = (node, key) => { if (node === null) { return false; } if (key === node.key) { return true; } else if (key < node.key) { return searchNode(node.left, key); } else { return searchNode(node.right, key); } } this.search = key => { searchNode(root, key); } const inOrderTraverseNode = (node, callback) => { if (node) { inOrderTraverseNode(node.left, callback); callback(node); inOrderTraverseNode(node.right, callback); } } this.inOrderTraverse = callback => { inOrderTraverseNode(root, callback) } const preOrderTraverseNode = (node, callback) => { if (node) { callback(node); preOrderTraverseNode(node.left, callback); preOrderTraverseNode(node.right, callback); } } this.preOrderTraverse = callback => { preOrderTraverseNode(root, callback); } const postOrderTraverseNode = (node, callback) => { if (node) { postOrderTraverseNode(node.left, callback); postOrderTraverseNode(node.right, callback); callback(node); } } this.postOrderTraverse = callback => { postOrderTraverseNode(root, callback); } const minNode = node => { if (node) { while (node && node.left !== null) { node = node.left; } return node.key; } return null; } this.min = () => minNode(root) const maxNode = node => { if (node) { while (node && node.right !== null) { node = node.right; } return node.key; } return null; } this.max = () => maxNode(root) const removeNode = (node, key) => { if (node) { if (node.key === key) { if (node.left === null && node.right === null) { return null; } else if (node.left === null && node.right !== null) { return node.right; } else if (node.left !== null && node.right === null) { return node.left; } else { const min = minNode(node.right); node.key = min; node.right = removeNode(node.right, min); return node; } } else if (key < node.key) { node.left = removeNode(node.left, key); return node; } else { node.right = removeNode(node.right, key); return node; } } return null; } this.remove = key => { root = removeNode(root, key); } }
|