C# solution using a queue


  • 0
    S

    C# solution using a Queue for the level-order traversal, and another queue to maintain the level order for output.

    public class Solution {
        public IList<IList<int>> LevelOrder(TreeNode root) {
    * list item
            IList<IList<int>> ans = new List<IList<int>>();
            
            if (root == null) 
                return ans;
            
            Queue<TreeNode> q = new Queue<TreeNode>();
            Queue<int> level = new Queue<int>();
            q.Enqueue(root);
            level.Enqueue(0);
            
            while (q.Count > 0)
            {
                TreeNode temp = q.Dequeue();
                int l = level.Dequeue();
                
                if (ans.Count > l)
                    ans[l].Add(temp.val);
                else
                    ans.Add(new List<int>() { temp.val });
                
                if (temp.left != null) {
                    q.Enqueue(temp.left);
                    level.Enqueue(l+1);
                }
                if (temp.right != null)  {
                    q.Enqueue(temp.right);
                    level.Enqueue(l+1);
                }
            }
            return ans;
        }
    }
    

Log in to reply
 

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