|
| 1 | +const Node = require('./Node'); |
| 2 | + |
| 3 | +class BinaryTree { |
| 4 | + constructor(arr) { |
| 5 | + if (!Array.isArray(arr) || !arr.length) { |
| 6 | + throw new Error('Invalid argument to create a Binary Tre'); |
| 7 | + } |
| 8 | + this.root = this.createBinaryTree((this.root = null), arr, 0); |
| 9 | + } |
| 10 | + |
| 11 | + // eslint-disable-next-line class-methods-use-this |
| 12 | + createBinaryTree(root, arr, i) { |
| 13 | + if (i < arr.length) { |
| 14 | + // eslint-disable-next-line no-param-reassign |
| 15 | + root = new Node(arr[i]); |
| 16 | + // eslint-disable-next-line no-param-reassign |
| 17 | + root.leftChild = this.createBinaryTree(root.leftChild, arr, 2 * i + 1); |
| 18 | + // eslint-disable-next-line no-param-reassign |
| 19 | + root.rightChild = this.createBinaryTree(root.rightChild, arr, 2 * i + 2); |
| 20 | + } |
| 21 | + return root; |
| 22 | + } |
| 23 | + |
| 24 | + traversePreorder(root) { |
| 25 | + let arr = []; |
| 26 | + |
| 27 | + if (root === null) return arr; |
| 28 | + // push node to arr |
| 29 | + arr.push(root.value); |
| 30 | + |
| 31 | + // push left node |
| 32 | + const left = this.traversePreorder(root.leftChild); |
| 33 | + arr = [...arr, ...left]; |
| 34 | + |
| 35 | + // push right node |
| 36 | + const right = this.traversePreorder(root.rightChild); |
| 37 | + arr = [...arr, ...right]; |
| 38 | + |
| 39 | + return arr; |
| 40 | + } |
| 41 | + |
| 42 | + preOrder() { |
| 43 | + return this.traversePreorder(this.root); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// const bt = new BinaryTree([1, 2, 3, 4, 5, 6]); |
| 48 | +// console.log(bt.root); |
| 49 | +// console.log(bt.preOrder()); |
| 50 | + |
| 51 | +module.exports = BinaryTree; |
0 commit comments