Given 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 children is separated by the null value (See examples).
Follow up:
Recursive solution is trivial, could you do it iteratively?
Example 1:
Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4]
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
Constraints:
- The height of the n-ary tree is less than or equal to
1000
- The total number of nodes is between
[0, 10^4]
N叉树的前序遍历。题目就是题意,同时followup问能不能用迭代的做法做。我这里给出迭代和递归的两种不同做法。其中迭代是DFS做的。
迭代DFS
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public List<Integer> preorder(Node root) { 3 List<Integer> res = new ArrayList<>(); 4 // corner case 5 if (root == null) { 6 return res; 7 } 8 9 // normal case 10 Stack<Node> stack = new Stack<>(); 11 stack.push(root); 12 while (!stack.isEmpty()) { 13 Node cur = stack.pop(); 14 for (int i = cur.children.size() - 1; i >= 0; i--) { 15 stack.push(cur.children.get(i)); 16 } 17 res.add(cur.val); 18 } 19 return res; 20 } 21 }
JavaScript实现
1 /** 2 * @param {Node} root 3 * @return {number[]} 4 */ 5 var preorder = function (root) { 6 let res = []; 7 // corner case 8 if (root === null) { 9 return res; 10 } 11 12 // normal case 13 let stack = [root]; 14 while (stack.length) { 15 let cur = stack.pop(); 16 let size = cur.children.length; 17 for (let i = size - 1; i >= 0; i--) { 18 stack.push(cur.children[i]); 19 } 20 res.push(cur.val); 21 } 22 return res; 23 };
递归
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public List<Integer> preorder(Node root) { 3 List<Integer> res = new ArrayList<>(); 4 // corner case 5 if (root == null) { 6 return res; 7 } 8 helper(root, res); 9 return res; 10 } 11 12 private void helper(Node root, List<Integer> res) { 13 if (root == null) { 14 return; 15 } 16 res.add(root.val); 17 for (Node child : root.children) { 18 helper(child, res); 19 } 20 } 21 }
JavaScript实现
1 /** 2 * @param {Node} root 3 * @return {number} 4 */ 5 var preorder = function (root) { 6 let res = []; 7 if (root === null) { 8 return res; 9 } 10 helper(res, root); 11 return res; 12 }; 13 14 var helper = function (res, root) { 15 if (root === null) { 16 return; 17 } 18 res.push(root.val); 19 for (let child of root.children) { 20 helper(res, child); 21 } 22 };