C
C#16mo ago
morry329#

✅ A LeetCode glitch or am I wrong with my code?

So again this is the LC puzzle https://leetcode.com/problems/binary-tree-level-order-traversal/description/ My solution is as follows;
`public class Solution {
public IList<IList<int>> LevelOrder(TreeNode root) {
List<IList<int>> res = new List<IList<int>>();
if(root == null){
return res;
}

Queue<TreeNode> q = new Queue<TreeNode>();
List<int> separation = new List<int>();
q.Enqueue(root);
while(q.Count > 0){

separation = new List<int>();
int count = q.Count;
for(int i = 0; i < count; i++){
var curr = q.Dequeue();

if(curr.left != null){
q.Enqueue(curr.left);
}

if(curr.right != null){
q.Enqueue(curr.right);
}
separation.Add(curr.val);
}
res.Add(separation);
}
return res;
}
}
`public class Solution {
public IList<IList<int>> LevelOrder(TreeNode root) {
List<IList<int>> res = new List<IList<int>>();
if(root == null){
return res;
}

Queue<TreeNode> q = new Queue<TreeNode>();
List<int> separation = new List<int>();
q.Enqueue(root);
while(q.Count > 0){

separation = new List<int>();
int count = q.Count;
for(int i = 0; i < count; i++){
var curr = q.Dequeue();

if(curr.left != null){
q.Enqueue(curr.left);
}

if(curr.right != null){
q.Enqueue(curr.right);
}
separation.Add(curr.val);
}
res.Add(separation);
}
return res;
}
}
But one line of code bothers me still. This one int count = q.Count;` If I do like this instead of initialising the integer count:
while(q.Count > 0){

separation = new List<int>();
for(int i = 0; i < q.Count; i++){
//DO STUFF
}
}
while(q.Count > 0){

separation = new List<int>();
for(int i = 0; i < q.Count; i++){
//DO STUFF
}
}
` I get this result
Output [[3,9],[20,15],[7]] //was supposed to be [[3],[9,20],[15,7]]
Output [[3,9],[20,15],[7]] //was supposed to be [[3],[9,20],[15,7]]
` Could anyone kindly tell me it is a glitch on LC or am I wrong? (if I am wrong I appreciate it if you could point out which part of my code is wrong)
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.
2 Replies
Matt
Matt16mo ago
that evaluation (i < q.Count) runs every iteration so if you enqueue/dequeue stuff in q, you will end up with a different count every few iterations meanwhile, doing int count = q.Count; before the loop ensures its value doesn't change while you're iterating
morry329#
morry329#16mo ago
Ahhhhhh I see! Thank you so much for pointing me that out 🙏 I see the error more clearly now 🔮