[topic address]
Given an n-tree, returns a sequential traversal of its node values.
The n-fork tree is serialized in the input as a sequential traversal, with each set of child nodes separated by null values (see example).
Advanced:
Recursion is easy. Can you do it iteratively?
Example 1:
Input: root = [1, null, 3 4-trichlorobenzene, null, 5, 6] output:,3,5,6,2,4 [1]Copy the code
Example 2:
Input: root = [1, null, 2, 5-tetrafluorobenzoic, null, null, 6, 7, null, 8, null, 9, 10, null, null, 11, null, 12, null, 13, null, null, 14] output: ,2,3,6,7,11,14,4,8,12,5,9,13,10 [1]Copy the code
Tip:
- The height of an n-tree is less than or equal to
1000
- The total number of nodes is in range
[0, 10 ^ 4)
内
Recursive problem solving
First, the recursive method is simple, just processing the current node, and then recursively processing the array of children of the current node
The code is as follows:
Var preorder = function(root) {const res = []; Function _preorder(root){if(root === null) return; // Process the current node res.push(root.val); For (let I = 0; i<root.children.length; i++){ _preorder(root.children[i]) } } _preorder(root); // return result array return res; };Copy the code
Iterative solution
The iterative algorithm traverses the n-tree in the same way as the previous leetcode-144-binary tree preorder traversal-iteration algorithm
When the current node is not empty, keep it equal to the left subtree, and stack unprocessed nodes
When the current node is empty, the top element of the stack is processed
If the current node is empty and the stack is empty, the traversal of the N-tree is complete. Exit the loop and return the result array
The animation is shown below:
The code is as follows:
Var preorder = function(root) {const stack = [],res = []; / / the current node is not null or stack is not empty, tree traversal N fork while (root | | stack. The length) {/ / when the node is not null while (root) {/ / the current node values into the array res. Push (root. Val); For (let I = root.children. Length -1; i>0; I --){stack.push(root.children[I])} root = root.children[0]; } // Handle top node root = stack.pop(); } // return result array return res; }Copy the code
At this point we have completed the prior traversal of the leetcode-589-n fork tree
If you have any questions or suggestions, please leave a comment!