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
| class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } }
class BinaryTree { constructor() { this._root = null; }
insert(data, node = this._root) { let newNode = new Node(data); if (node === null) { this._root = newNode; } else { if (data > node.data) { let temp = data; data = node.data; node.data = temp; this.insert(data, node); } else { if (!node.left) { return node.left = new Node(data); } if (!node.right) { return node.right = new Node(data); } if (node.left && node.left.data <= data) { this.insert(data, node.left); } else { this.insert(data, node.right); } } } }
inOrder(callback, node = this._root) { if (node === null) { return; } if (node.left) { this.inOrder(callback, node.left); } callback(node); if (node.right) { this.inOrder(callback, node.right); } }
preOrder(callback, node = this._root) { if (node === null) { return; } callback(node); if (node.left) { this.preOrder(callback, node.left); } if (node.right) { this.preOrder(callback, node.right); } }
postOrder(callback, node = this._root) { if (node === null) { return; } if (node.left) { this.postOrder(callback, node.left); } if (node.right) { this.postOrder(callback, node.right); } callback(node); }
levelOrder(callback, node = this._root) { if (node === null) { return; } let queue = []; queue.push(node); while (queue.length > 0) { let curr = queue.shift(); callback(curr); curr.left && queue.push(curr.left); curr.right && queue.push(curr.right); } }
remove(data, node = this._root) { if (node === null) { return null; } if (this._root.data === data) { let curr = this._root; this._root = null; return curr; } if (node.left) { let curr = node.left; if (curr.data === data) { node.left = null; return curr; } else { this.remove(data, node.left); } } if (node.right) { let curr = node.right; if (curr.data === data) { node.right = null; return curr; } else { this.remove(data, node.right); } } }
toString() { return JSON.stringify(this._root); } }
|