SOURCE

class Root {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}


function getTree(first, middle) {
    if (!first.length || !middle.length) return null;
    const m = middle.indexOf(first[0]);
    const root = new Root(first[0]);
    root.left = getTree(first.slice(1, m + 1), middle.slice(0, m));
    root.right = getTree(first.slice(m + 1), middle.slice(m + 1));
    return root;
}

const ans = [];

function traverse(root) {
    if (root.left) traverse(root.left);
    if (root.right) traverse(root.right);
    ans.push(root.val);
}

const first = [1, 2, 4, 3, 6];
const middle = [4, 2, 1, 3, 6];

const tree = getTree(first, middle)
traverse(tree);
console.log(ans);
console 命令行工具 X clear

                    
>
console