对比代码2,代码1存在的问题以及解决方式
//代码1
var preorderTraversal = function (root) {
if (!root) return;//若当前结点为空停止继续遍历
const stack = [root];
const res = [];
//只传递一个参数使用闭包保存结果
const preOrder = function (root) {
// 使用cur变量临时保存栈弹出元素
let cur = null;
while (stack.length) {
cur = stack.pop();
res.push(cur.val);
// 模拟出入栈过程,前序遍历是根左右,需要右先进栈才能右后出栈
cur.right && stack.push(cur.right);
cur.left && stack.push(cur.left);
}
}
preOrder(root);
return res;
};
//代码2
var preorderTraversal = function(root, res = []) {
if(!root) return res;
const stack = [root];
let cur = null;
while(stack.length) {
cur = stack.pop();
res.push(cur.val);
cur.right && stack.push(cur.right);
cur.left && stack.push(cur.left);
}
return res;
};