simple c# iteration solution


  • 0
    N
    public class Solution {
        public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
            var list = new List<IList<int>>();
            if (root == null) return list;
            
            var q = new Queue<TreeNode>();
            q.Enqueue(root);
            var level = 0;
            while(q.Count>0){
                var count = q.Count;
                var l = new List<int>();
                for(var i=0;i<count;i++){
                    var node = q.Dequeue();
                    if(level%2==0){
                        l.Add(node.val);
                    }
                    else{
                        l.Insert(0, node.val);
                    }
                    if(node.left!=null) q.Enqueue(node.left);
                    if(node.right!=null) q.Enqueue(node.right);
                }
                level++;
                list.Add(l);
            }
            
            return list;
        }
    }
    

Log in to reply
 

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