C# Solution with Queue and List Insert at Position. No need to reverse List


  • 0
    S

    C# solution using Queue and List.Insert at begining ... No need to reverse list at End.

    public IList<IList<int>> LevelOrderBottom(TreeNode root) 
    {
        var result = new List<IList<int>>();
        if(root == null) return result;
        
        var queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        
        while(true)
        {
            // use the Queue count when we have completed one level
            int nodeCount = queue.Count;
            if(nodeCount == 0)
            {
                break;
            }
            
            var subList = new List<int>();
            while(nodeCount > 0)
            {
                var dataNode = (TreeNode)queue.Dequeue();
                
                subList.Add(dataNode.val);
                
                if(dataNode.left != null)
                {
                    queue.Enqueue(dataNode.left);
                }
                
                if(dataNode.right != null)
                {
                    queue.Enqueue(dataNode.right);
                }
                
                nodeCount--;
            }
            
           // always insert the new list at the beginning
            result.Insert(0, subList);
        }
        
        return result;
    }

Log in to reply
 

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