|
| 1 | +class Node { |
| 2 | + constructor(data) { |
| 3 | + this.data = data; |
| 4 | + this.left = null; |
| 5 | + this.right = null; |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +class BinaryTree { |
| 10 | + constructor() { |
| 11 | + this.root = null; |
| 12 | + } |
| 13 | + |
| 14 | + insert(data) { |
| 15 | + const newNode = new Node(data); |
| 16 | + |
| 17 | + if (this.root === null) { |
| 18 | + this.root = newNode; |
| 19 | + } else { |
| 20 | + this.insertNode(this.root, newNode); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + insertNode(node, newNode) { |
| 25 | + if (newNode.data < node.data) { |
| 26 | + if (node.left === null) { |
| 27 | + node.left = newNode; |
| 28 | + } else { |
| 29 | + this.insertNode(node.left, newNode); |
| 30 | + } |
| 31 | + } else { |
| 32 | + if (node.right === null) { |
| 33 | + node.right = newNode; |
| 34 | + } else { |
| 35 | + this.insertNode(node.right, newNode); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + remove(data) { |
| 41 | + this.root = this.removeNode(this.root, data); |
| 42 | + } |
| 43 | + |
| 44 | + removeNode(node, key) { |
| 45 | + if (node === null) { |
| 46 | + return null; |
| 47 | + } else if (key < node.data) { |
| 48 | + node.left = this.removeNode(node.left, key); |
| 49 | + } else if (key > node.data) { |
| 50 | + node.right = this.removeNode(node.right, key); |
| 51 | + } else { |
| 52 | + if (node.left === null && node.right === null) { |
| 53 | + node = null; |
| 54 | + } else if (node.left === null) { |
| 55 | + node = node.right; |
| 56 | + } else if (node.right === null) { |
| 57 | + node = node.left; |
| 58 | + } else { |
| 59 | + const childRight = node.right; |
| 60 | + |
| 61 | + this.insertNode(childRight, node.left); |
| 62 | + node = childRight; |
| 63 | + } |
| 64 | + } |
| 65 | + return node; |
| 66 | + } |
| 67 | + |
| 68 | + preorder(fn, node = this.root) { |
| 69 | + if (node !== null) { |
| 70 | + fn(node); |
| 71 | + this.preorder(fn, node.left); |
| 72 | + this.preorder(fn, node.right); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + inorder(fn, node = this.root) { |
| 77 | + if (node !== null) { |
| 78 | + this.preorder(fn, node.left); |
| 79 | + fn(node); |
| 80 | + this.preorder(fn, node.right); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + postorder(fn, node = this.root) { |
| 85 | + if (node !== null) { |
| 86 | + this.preorder(fn, node.left); |
| 87 | + this.preorder(fn, node.right); |
| 88 | + fn(node); |
| 89 | + } |
| 90 | + } |
| 91 | +} |
0 commit comments