using System;
using System.Collections.Generic;
public class MaxSpiralSum
{
static int maxSum(List<int> arr)
{
int max_ending_here = int.MinValue;
int max_so_far = int.MinValue;
for (int i = 0; i < arr.Count; i++)
{
if (max_ending_here < 0)
max_ending_here = arr[i];
else
max_ending_here +=arr[i];
max_so_far = Math.Max(max_so_far, max_ending_here);
}
return max_so_far;
}
public static int maxSpiralSum(Node root)
{
if (root == null)
return 0;
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
List<int> arr=new List<int>();
s1.Push(root);
while (s1.Count != 0 || s2.Count != 0)
{
while (s1.Count != 0)
{
Node temp = s1.Pop();
arr.Add(temp.data);
if (temp.right != null)
s2.Push(temp.right);
if (temp.left != null)
s2.Push(temp.left);
}
while (s2.Count != 0)
{
Node temp = s2.Pop();
arr.Add(temp.data);
if (temp.left != null)
s1.Push(temp.left);
if (temp.right != null)
s1.Push(temp.right);
}
}
return maxSum(arr);
}
public static void Main(String []args)
{
Node root = new Node(-2);
root.left = new Node(-3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(1);
root.right.left = new Node(-2);
root.right.right = new Node(-1);
root.left.left.left = new Node(-3);
root.right.right.right = new Node(2);
Console.Write("Maximum Spiral Sum = " +
maxSpiralSum(root));
}
}
public class Node
{
public int data ;
public Node left, right ;
public Node(int data)
{
this.data = data;
left = right = null;
}
};