解法一:递归版
要注意,在用递归法做前序遍历的时候,需要声明一个数组,将所有值按顺序push进去。
所以要将数组的声明放在函数体的外面,return也是,以此形成一个闭包,函数体中push的最后结果将会被返回。
如果将数组声明和return都写在函数体中,有几个元素被push进去将会产生几个数组
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let res=[]
const preorder=(n)=> {
if(!n) {return [];}
res.push(n.val)
if(n.left) preorder(n.left)
if(n.right) preorder(n.right)
}
preorder(root)
return res
};
解法二:非递归版
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
if(!root) {return [];}
const stack=[root];
const res=[]
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
};