1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| const middle = ['F', 'C', 'G', 'A', 'D', 'B', 'E']; const last = ['F', 'G', 'C', 'D', 'E', 'B', 'A'];
function Node(value) { this.value = value; this.leftChild = null; this.rightChild = null; }
function middleLastToTree(middle, last) { if (middle === null || last === null || middle.length === 0 || last.length === 0 || middle.length !== last.length) return; const root = new Node(last[last.length - 1]); const rootIndex = middle.indexOf(root.value); const lastLeft = last.slice(0, rootIndex); const lastRight = last.slice(rootIndex, last.length - 1); const middleLeft = middle.slice(0, rootIndex); const middleRight = middle.slice(rootIndex + 1); root.leftChild = middleLastToTree(middleLeft, lastLeft); root.rightChild = middleLastToTree(middleRight, lastRight); return root; }
|