[LeetCode] 589. N-ary Tree Preorder Traversal

多叉树的先序遍历。题意很直观,就是给一个多叉树,请你输出先序遍历的结果。跟二叉树的先序遍历一样,还是两种做法,BFS和DFS。两种做法的时间复杂度是O(n),空间复杂度是O(h)。例子,

[LeetCode] 589. N-ary Tree Preorder Traversal_第1张图片

 

Input: root = [1,null,3,2,4,null,5,6]

Output: [1,3,5,6,2,4]

 

BFS

 1 /**
 2  * @param {Node} root
 3  * @return {number[]}
 4  */
 5 var preorder = function (root) {
 6     let res = [];
 7     if (root === null) return res;
 8     let stack = [root];
 9     while (stack.length) {
10         let cur = stack.pop();
11         let size = cur.children.length;
12         for (let i = size - 1; i >= 0; i--) {
13             stack.push(cur.children[i]);
14         }
15         res.push(cur.val);
16     }
17     return res;
18 };

 

DFS

 1 /**
 2  * @param {Node} root
 3  * @return {number}
 4  */
 5 var preorder = function (root) {
 6     let res = [];
 7     if (root === null) return res;
 8     helper(res, root);
 9     return res;
10 };
11 
12 var helper = function (res, root) {
13     if (root === null) return;
14     res.push(root.val);
15     for (let child of root.children) {
16         helper(res, child);
17     }
18 }

你可能感兴趣的:([LeetCode] 589. N-ary Tree Preorder Traversal)