C#C
C#3y ago
morry329#

✅ Case1 Failed: LeetCode Binary Tree Level Order Traversal

So I am studying some solutions from this puzzle https://leetcode.com/problems/binary-tree-level-order-traversal/solutions/?envType=study-plan&id=level-1&languageTags=csharp

My current code is like this
public class Solution {
    public IList<IList<int>> LevelOrder(TreeNode root) {
        List<IList<int>> res = new();
        List<int> separation = new();
        if(root == null){
            return res;
        }
        Queue<TreeNode> q = new Queue<TreeNode>();
        q.Enqueue(root);
        int levelCount = 1;
        while(q.Count > 0){
            TreeNode visited = q.Dequeue();
            
                if(visited.left != null){
                    q.Enqueue(visited.right);

                }

                if(visited.right != null){

                    q.Enqueue(visited.left);
                }
                separation.Add(visited.val);
                levelCount--;
                if(levelCount == 0){
                    res.Add(separation);
                    levelCount = q.Count;
                    
                }
        }
        return res;


    }
}


But I get the following incorrect result (see the attached screenshot)

Could anyone kindly tell me what my code has done wrong?
Bildschirmfoto_2023-03-10_um_21.42.12.png
LeetCode
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.
Was this page helpful?