编辑代码

// leetcode-144 二叉树的前序遍历

/*
    使用栈实现
*/

function preorderTraversal (root) {
    const res = []
    const stack = []

    if (root) stack.push(root)

    while (stack.length) {
        const n = stack.pop()

        res.push(n.val)

        if (n.right) stack.push(n.right)
        if (n.left) stack.push(n.left)
    }

    return res
}

const root = {
    val: 'a',
    left: {
        val: 'b',
        right: {
            val: 'c'
        }
    },
    right: {
        val: 'd',
        left: {
            val: 'e',
        }
    }
}

/*
            a
           / \
         b     d
      /  \    /  \
         c   e    

 */

console.log(preorderTraversal(root)) // ['a'. 'b', 'c', 'd', 'e']