Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given the root
of 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)
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:
[0, 104]
.0 <= Node.val <= 104
1000
.class Solution {
public List<Integer> preorder(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.add(root);
while (!stack.empty()) {
root = stack.pop();
list.add(root.val);
for (int i = root.children.size() - 1; i >= 0; i--)
stack.add(root.children.get(i));
}
return list;
}
}
class Solution {
private:
void travel(Node* root, vector<int>& result) {
if (root == nullptr) {
return;
}
result.push_back(root -> val);
for (Node* child : root -> children) {
travel(child, result);
}
}
public:
vector<int> preorder(Node* root) {
vector<int> result;
travel(root, result);
return result;
}
};
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
output =[]
# perform dfs on the root and get the output stack
self.dfs(root, output)
# return the output of all the nodes.
return output
def dfs(self, root, output):
# If root is none return
if root is None:
return
# for preorder we first add the root val
output.append(root.val)
# Then add all the children to the output
for child in root.children:
self.dfs(child, output)
In our experience, we suggest you solve this N-ary Tree Preorder Traversal LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the N-ary Tree Preorder Traversal LeetCode Solution
I hope this N-ary Tree Preorder Traversal LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>