LeetCode: N Ary Tree Preorder Traversal Solution

Implementation

1/**
2 * // Definition for a Node.
3 * function Node(val, children) {
4 * this.val = val;
5 * this.children = children;
6 * };
7 */
8
9/**
10 * @param {Node} root
11 * @return {number[]}
12 */
13var preorder = function (root) {
14 const res = []
15
16 const traverse = node => {
17 if (!node) return
18
19 res.push(node.val)
20 node.children.forEach(traverse)
21 }
22
23 traverse(root)
24
25 return res
26}

References

Original problem

Comments

Loading comments...

Tags

leetcode

tree

Next Post

LeetCode: Triangle

Memoized recursion

HoningJS

Search Posts