C# Solution


  • 0
    if (root == null)
                return new List<IList<int>>();
            
            IList<IList<int>> results = new List<IList<int>>();
            IList<int> resultInLevel = new List<int>();
            Stack<TreeNode> oddLevel = new Stack<TreeNode>();
            Stack<TreeNode> evenLevel = new Stack<TreeNode>();
            int level = 1;
            TreeNode currentNode = null;
            
            oddLevel.Push(root);
            
            while (oddLevel.Count != 0 || evenLevel.Count != 0)
            {
                resultInLevel = new List<int>();
                
                if (level % 2 != 0)
                {
                    while(oddLevel.Count() != 0)
                    {
                        currentNode = oddLevel.Pop();
                        
                        if (currentNode.left != null)
                            evenLevel.Push(currentNode.left);
                        if (currentNode.right != null)
                            evenLevel.Push(currentNode.right);
                            
                        resultInLevel.Add(currentNode.val);
                    }
                }
                else
                {
                    while(evenLevel.Count() != 0)
                    {
                        currentNode = evenLevel.Pop();
                        
                        if (currentNode.right != null)
                            oddLevel.Push(currentNode.right);
                        if (currentNode.left != null)
                            oddLevel.Push(currentNode.left);
                        
                        resultInLevel.Add(currentNode.val);
                    }
                }
                
                results.Add(resultInLevel);
                level++;
            }
            
            return results;
    

Log in to reply
 

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