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
| class Node { constructor(data) { this.data = data; this.parent = null; this.children = []; } }
class Tree { constructor() { this._root = null; }
add(data, toData) { if (toData === null) { return this._root = new Node(data); } let target = this.getNodeByData(toData, this.deepTravers); if (target !== null) { let newNode = new Node(data); newNode.parent = target.data; target.children.push(newNode); } else { console.log(`Can not add to ${toData}`); } }
remove(data, toData) { let target = this.getNodeByData(toData, this.breadthTravers); if (target !== null) { let index = 0; for (let i = 0; i < target.children.length; i++) { if (data === target.children[i].data) { index = i; break; } } return target.children.splice(index, 1); } else { console.log(`Can not find ${data} from ${toData}`); } }
deepTravers(callback) { const travers = (node) => { callback(node); for (let i = 0; i < node.children.length; i++) { travers(node.children[i]); } } travers(this._root); }
breadthTravers(callback) { let queue = []; queue.push(this._root); while (queue.length > 0) { let curr = queue.shift(); callback(curr); for (let i = 0; i < curr.children.length; i++) { queue.push(curr.children[i]); } } }
containes(data, travers) { let contain = false; travers.call(this, (node) => { console.log(node.data, data); if (node.data === data) { contain = true; } }); return contain; }
getNodeByData(data, travers) { let result = null; travers.call(this, (node) => { if (node.data === data) { result = node; } }); return result; }
toString() { return JSON.stringify(this._root); } }
|