2019-03-21-n-ary tree preorder traversal

题目,589. N-ary Tree Preorder Traversal

解析

n叉树的前序遍历,根->左->右
先push根,然后遍历子树,使用前序递归子树。注意数组的拼接。

1
2
3
4
5
6
7
8
9
10
11
var preorder = function(root) {
const res = [];
if(!root) {
return [];
}
res.push(root.val)
for(let i=0; i<root.children.length; i++) {
res.push(...preorder(root.children[i]));
}
return res;
};