C# solution: BFS


  • 0
    B
    public class Solution 
    {
        public IList<IList<int>> ZigzagLevelOrder(TreeNode root) 
        {
            var result = new List<IList<int>>();
            if (root == null) return result;
    
            var depth = 0;
    
            var queue = new Queue<TreeNode>();
            queue.Enqueue(root);
    
            while(queue.Any())
            {
                var size = queue.Count;
                
                var oneResult = new List<int>();
                for (int z = 0; z < size; z++)
                {
                    var cur = queue.Dequeue();
    
                    if (depth % 2 == 0)     oneResult.Add(cur.val);
                    else                    oneResult.Insert(0, cur.val);
    
                    if (cur.left != null) queue.Enqueue(cur.left);
                    if (cur.right != null) queue.Enqueue(cur.right);
                }
                
                depth++;
                result.Add(oneResult);
            }
    
            return result;
        }
    }
    

Log in to reply
 

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