C
C#2y ago
morry329#

❔ ✅ Missing a first element of the output

So I am on this LeetCode puzzle https://leetcode.com/problems/n-ary-tree-preorder-traversal/?envType=study-plan&id=level-1 My code is here right now
public class Solution {
public IList<int> Preorder(Node root) {
List<int> ans = new List<int>();
if(root == null){
return ans;
}
Helper(root, ans);
return ans;

}

public void Helper(Node root, List<int> ans){
foreach(var node in root.children){

ans.Add(node.val);
Helper(node, ans);
}
}
}
public class Solution {
public IList<int> Preorder(Node root) {
List<int> ans = new List<int>();
if(root == null){
return ans;
}
Helper(root, ans);
return ans;

}

public void Helper(Node root, List<int> ans){
foreach(var node in root.children){

ans.Add(node.val);
Helper(node, ans);
}
}
}
It is still missing a first element in the List array as per screenshot. Could anyone kindly tell me why?
LeetCode
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
7 Replies
rotor_
rotor_2y ago
@morry329 you seem to have forgotten the root node
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
morry329#
morry329#OP2y ago
Thanks a lot - just one more question. So I have added the root node in the PreOrder method, it worked:
public class Solution {
public IList<int> Preorder(Node root) {
List<int> ans = new List<int>();
if(root == null){
return ans;
}
ans.Add(root.val);
Helper(root, ans);
return ans;

}

public void Helper(Node root, List<int> ans){
foreach(var node in root.children){


ans.Add(node.val);

Helper(node,ans);
}
}
}
public class Solution {
public IList<int> Preorder(Node root) {
List<int> ans = new List<int>();
if(root == null){
return ans;
}
ans.Add(root.val);
Helper(root, ans);
return ans;

}

public void Helper(Node root, List<int> ans){
foreach(var node in root.children){


ans.Add(node.val);

Helper(node,ans);
}
}
}
rotor_
rotor_2y ago
...What's the question?
morry329#
morry329#OP2y ago
Sorry I forgot to delete the question part, I just resolved it myself 🙂
rotor_
rotor_2y ago
Ah nice congrats udidit
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server