C# Accepted solution using two stacks


  • 0
    J
    Stack<TreeNode> s1 = new Stack<TreeNode>();
        Stack<TreeNode> s2 = new Stack<TreeNode>();
        int count = 1;
         
        public IList<IList<int>> ZigzagLevelOrder(TreeNode root) 
        {
            var result = new List<IList<int>>();
            if (root == null) return result;
            
            s1.Push(root);
            while (s1.Count != 0 || s2.Count != 0)
            {
                var list = new List<int>();
                if (count % 2 == 0) // use stack 2
                {
                    while (s2.Count != 0)
                    {
                        var node = s2.Pop();
                        if (node.right != null) s1.Push(node.right);
                        if (node.left != null) s1.Push(node.left);
                        list.Add(node.val);
                    }
                }
                else // use stack 1
                {
                    while (s1.Count != 0)
                    {
                        var node = s1.Pop();
                        if (node.left != null) s2.Push(node.left); 
                        if (node.right != null) s2.Push(node.right);
                        list.Add(node.val);
                    }
                }
                result.Add(list);
                count++;
            }
            return result;
        }
    

Log in to reply
 

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