Beating 94.57% of c# submissions


  • 1
    I
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public IList<IList<int>> LevelOrder(TreeNode root) {
            List<IList<int>> list = new List<IList<int>>();
            
            if(root != null) 
            {
                List<int> tempList = new List<int>();
                Queue<TreeNode> q = new Queue<TreeNode>();
                
                q.Enqueue(root);
                q.Enqueue(null);
                
                TreeNode temp = null;
                
                while(q.Count > 0)
                {
                    temp = q.Dequeue();
                    
                    if(temp != null)
                    {
                        if(temp.left != null)
                        {
                            q.Enqueue(temp.left);
                        }
                        
                        if(temp.right != null)
                        {
                            q.Enqueue(temp.right);
                        }
                        
                        tempList.Add(temp.val);
                    }
                    else
                    {
                        if(q.Count == 0)
                        {
                            list.Add(tempList);
                            break;
                        }
                        else
                        {
                            q.Enqueue(null);
                            list.Add(tempList);
                            tempList = new List<int>();
                        }
                    }
                }
                
            }
            
            return list;
        }
    }```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.