PS/LeetCode
LeetCode / Tree / 589번 / N-ary Tree Preorder Traversal / JS
KimMinJun
2023. 4. 5. 16:03
N-ary Tree Preorder Traversal - LeetCode
Can you solve this real interview question? N-ary Tree Preorder Traversal - Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of chil
leetcode.com
< 문제 간단설명 >
전위순회로 트리를 탐색하는 문제이다. 전위순회의 순서는 왼쪽 하위노드 -> 루트 -> 오른쪽 하위노드의 순서이다.
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number[]}
*/
var preorder = function(root) {
let result = [];
const traversal = (root) => {
if(root === null) return;
result.push(root.val);
root.children.forEach((node) => {
traversal(node);
});
}
traversal(root);
return result;
};