递归写法:
const preorderTraversal = function (root) {
if (!root) {
return []
}
let res = []
res.push(root.val)
res = res.concat(preorderTraversal(root.left))
res = res.concat(preorderTraversal(root.right))
return res
}
递归优雅版:
var preorderTraversal = function(root) {
return root ? [root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right)] : []
};
迭代写法:
const preorderTraversal = function (root) {
let res = []
let stack = []
if (root) stack.push(root)
while (stack.length > 0) {
const n = stack.pop()
res.push(n.val)
if (n.right) stack.push(n.right)
if (n.left) stack.push(n.left)
}
return res
}