LeetCode 144. 二叉树的前序遍历 easy
主要是记录
- JS 的作用域的问题
- JS 闭包的使用
坑:
由于 result
的作用域是全局作用域,因此,如果不限制作用域的话,就会导致 result 内容越来越多。
解决:使用闭包,限制 result 的作用域
var preorderTraversal = function(root) {
let result = []
// 使用闭包来限制result的作用域,因为如果不用
// 多次调用的时候,result 初始值会逐渐增多
const preorder = function(root){
if(root == null){
return []
}
result.push(root.val)
preorder(root.left)
preorder(root.right)
}
preorder(root) // 调用闭包
return result
};