C# accepted solution - two stacks


  • 0
    R
    public IList<IList<int>> ZigzagLevelOrder(TreeNode root)
    {
    	IList<IList<int>> levelOrder = new List<IList<int>>();
    	Stack<TreeNode> stack1 = new Stack<TreeNode>();
    	Stack<TreeNode> stack2 = new Stack<TreeNode>();
    	if (root != null) stack1.Push(root);
    	bool isOddRow = true;
    	while (stack1.Count != 0 || stack2.Count != 0)
    	{
    		List<int> levelNums = new List<int>();
    		if (isOddRow)
    		{
    			var levelSize = stack1.Count;
    			while(stack1.Count !=0)
    			{
    				var poppedNode = stack1.Pop();
    				levelNums.Add(poppedNode.val);
    				if (poppedNode.left != null) stack2.Push(poppedNode.left);
    				if (poppedNode.right != null) stack2.Push(poppedNode.right);
    			}
    		}
    		else
    		{
    			while(stack2.Count != 0)
    			{
    				var poppedNode = stack2.Pop();
    				levelNums.Add(poppedNode.val);
    				if (poppedNode.right != null) stack1.Push(poppedNode.right);
    				if (poppedNode.left != null) stack1.Push(poppedNode.left);
    
    			}
    		}
    		isOddRow  = !isOddRow;
    		levelOrder.Add(levelNums);
    
    	}
    	return levelOrder;
    }

Log in to reply
 

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