[LeetCode] 589. N-ary Tree Preorder Traversal

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 589. N-ary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。

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

技术图片

 

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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode589. N-ary Tree Preorder Traversal

[LeetCode&Python] Problem 589. N-ary Tree Preorder Traversal

LeetCode 589. N叉树的前序遍历(N-ary Tree Preorder Traversal)

[LeetCode] 589. N-ary Tree Preorder Traversal_Easy

LeetCode 589 N-ary Tree Preorder Traversal 解题报告

[LeetCode] 589. N-ary Tree Preorder Traversal