前序遍历:根 --》左 --》 右
一、递归
var preorderTraversal = function(root) {
const res = [];
dfs(root);
return res;
function dfs(root) {
if (root == null) return;
res.push(root.val);
dfs(root.left);
dfs(root.right);
}
};
二、迭代
var preorderTraversal = function(root) {
const res = [], stack = [];
while (root || stack.length) {
while (root) {
res.push(root.val);
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return res;
};