编辑代码

function TreeNode(val, left, right) {
    this.val = val;
    this.left = left;
    this.right = right;
}
//前序遍历
var printBefore = function (list, node) {
    if (!node) {
        return;
    }
    list.push(node.val);
    printBefore(list, node.left);
    printBefore(list, node.right);
}
//中序遍历
var printCenter = function (list, node) {
    if (!node) {
        return;
    }
    printCenter(list, node.left);
    list.push(node.val);
    printCenter(list, node.right);
}
//后序遍历
var printAfter = function (list, node) {
    if (!node) {
        return;
    }
    printAfter(list, node.left);
    printAfter(list, node.right);
    list.push(node.val);
}
var preorderTraversal = function (root) {
    let list = [];
    printBefore(list, root) //前序遍历
    printCenter(list, root) //中序遍历
    printAfter(list, root) //后序遍历
    return list
};