Given a binary tree containing n nodes. The task is to find the maximum sum obtained when the tree is spirally traversed. In spiral traversal one by one all levels are being traversed with the root level traversed from right to left, then the next level from left to right, then further next level from right to left and so on.
Example:
Input:
Output: 7 Explanation: Maximum spiral sum = 4 + (-1) + (-2) + 1 + 5 = 7
Below is the implementation of the above approach:
C++
// C++ program to maximum // spiral sum in Binary Tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};intspiralSum(Node*root){if(root==nullptr)return0;stack<Node*>currentLevel,nextLevel;currentLevel.push(root);// variable to indicate direction // of traversal.boolleftToRight=false;// Array to store spiral traversal.vector<int>arr;while(!currentLevel.empty()){intsize=currentLevel.size();while(size--){Node*curr=currentLevel.top();currentLevel.pop();arr.push_back(curr->data);// if current direction to lor, then// push left node first, so that next // level traversal is rol.if(leftToRight){if(curr->left!=nullptr)nextLevel.push(curr->left);if(curr->right!=nullptr)nextLevel.push(curr->right);}else{if(curr->right!=nullptr)nextLevel.push(curr->right);if(curr->left!=nullptr)nextLevel.push(curr->left);}}// Flip the direction.leftToRight=!leftToRight;// Swap the stacks.swap(currentLevel,nextLevel);}intans=INT_MIN;// variable to store the sum of current subarray.intprev=0;// Performing kadane's algorithmfor(inti=0;i<arr.size();i++){// If the current subarray sum is less than// 0, then start a new subarrray from// index i.if(prev<0)prev=0;// include the current value into // the subarray sum.prev+=arr[i];// Compare the current subarray sum // with the maximum subarray sum.ans=max(ans,prev);}returnans;}intmain(){// Binary tree// -2// / \ // -3 4// / \ / \ // 5 1 -2 -1// / \ // -3 2Node*root=newNode(-2);root->left=newNode(-3);root->right=newNode(4);root->left->left=newNode(5);root->left->right=newNode(1);root->right->left=newNode(-2);root->right->right=newNode(-1);root->left->left->left=newNode(-3);root->right->right->right=newNode(2);cout<<spiralSum(root)<<endl;return0;}
Java
// Java program to maximum // spiral sum in Binary Treeimportjava.util.ArrayList;importjava.util.Stack;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{staticintspiralSum(Noderoot){if(root==null)return0;Stack<Node>currentLevel=newStack<>();Stack<Node>nextLevel=newStack<>();currentLevel.push(root);// variable to indicate direction // of traversal.booleanleftToRight=false;// Array to store spiral traversal.ArrayList<Integer>arr=newArrayList<>();while(!currentLevel.isEmpty()){intsize=currentLevel.size();while(size-->0){Nodecurr=currentLevel.pop();arr.add(curr.data);// if current direction to lor, then// push left node first, so that next // level traversal is rol.if(leftToRight){if(curr.left!=null)nextLevel.push(curr.left);if(curr.right!=null)nextLevel.push(curr.right);}else{if(curr.right!=null)nextLevel.push(curr.right);if(curr.left!=null)nextLevel.push(curr.left);}}// Flip the direction.leftToRight=!leftToRight;// Swap the stacks.Stack<Node>temp=currentLevel;currentLevel=nextLevel;nextLevel=temp;}intans=Integer.MIN_VALUE;// variable to store the sum of current subarray.intprev=0;// Performing kadane's algorithmfor(inti=0;i<arr.size();i++){// If the current subarray sum is less than// 0, then start a new subarray from// index i.if(prev<0)prev=0;// include the current value into // the subarray sum.prev+=arr.get(i);// Compare the current subarray sum // with the maximum subarray sum.ans=Math.max(ans,prev);}returnans;}publicstaticvoidmain(String[]args){// Binary tree// -2// / \// -3 4// / \ / \// 5 1 -2 -1// / \// -3 2Noderoot=newNode(-2);root.left=newNode(-3);root.right=newNode(4);root.left.left=newNode(5);root.left.right=newNode(1);root.right.left=newNode(-2);root.right.right=newNode(-1);root.left.left.left=newNode(-3);root.right.right.right=newNode(2);System.out.println(spiralSum(root));}}
Python
# Python program to maximum # spiral sum in Binary TreeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefspiralSum(root):ifrootisNone:return0currentLevel=[root]nextLevel=[]# variable to indicate direction # of traversal.leftToRight=False# Array to store spiral traversal.arr=[]whilecurrentLevel:size=len(currentLevel)whilesize>0:size-=1curr=currentLevel.pop()arr.append(curr.data)# if current direction to lor, then# push left node first, so that next # level traversal is rol.ifleftToRight:ifcurr.left:nextLevel.append(curr.left)ifcurr.right:nextLevel.append(curr.right)else:ifcurr.right:nextLevel.append(curr.right)ifcurr.left:nextLevel.append(curr.left)# Flip the direction.leftToRight=notleftToRight# Swap the lists.currentLevel,nextLevel=nextLevel,currentLevelans=float('-inf')# variable to store the sum of current # subarray.prev=0# Performing kadane's algorithmforiinarr:# If the current subarray sum is less than# 0, then start a new subarray from# index i.ifprev<0:prev=0# include the current value into # the subarray sum.prev+=i# Compare the current subarray sum # with the maximum subarray sum.ans=max(ans,prev)returnansif__name__=="__main__":# Binary tree# -2# / \# -3 4# / \ / \# 5 1 -2 -1# / \# -3 2root=Node(-2)root.left=Node(-3)root.right=Node(4)root.left.left=Node(5)root.left.right=Node(1)root.right.left=Node(-2)root.right.right=Node(-1)root.left.left.left=Node(-3)root.right.right.right=Node(2)print(spiralSum(root))
C#
// C# program to maximum // spiral sum in Binary TreeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{staticintspiralSum(Noderoot){if(root==null)return0;Stack<Node>currentLevel=newStack<Node>();Stack<Node>nextLevel=newStack<Node>();currentLevel.Push(root);// variable to indicate direction // of traversal.boolleftToRight=false;// List to store spiral traversal.List<int>arr=newList<int>();while(currentLevel.Count>0){intsize=currentLevel.Count;while(size-->0){Nodecurr=currentLevel.Pop();arr.Add(curr.data);// if current direction to lor, then// push left node first, so that next // level traversal is rol.if(leftToRight){if(curr.left!=null)nextLevel.Push(curr.left);if(curr.right!=null)nextLevel.Push(curr.right);}else{if(curr.right!=null)nextLevel.Push(curr.right);if(curr.left!=null)nextLevel.Push(curr.left);}}// Flip the direction.leftToRight=!leftToRight;// Swap the stacks.vartemp=currentLevel;currentLevel=nextLevel;nextLevel=temp;}intans=int.MinValue;// variable to store the sum of // current subarray.intprev=0;// Performing kadane's algorithmfor(inti=0;i<arr.Count;i++){// If the current subarray sum is less than// 0, then start a new subarray from// index i.if(prev<0)prev=0;// include the current value into // the subarray sum.prev+=arr[i];// Compare the current subarray sum // with the maximum subarray sum.ans=Math.Max(ans,prev);}returnans;}staticvoidMain(string[]args){// Binary tree// -2// / \// -3 4// / \ / \// 5 1 -2 -1// / \// -3 2Noderoot=newNode(-2);root.left=newNode(-3);root.right=newNode(4);root.left.left=newNode(5);root.left.right=newNode(1);root.right.left=newNode(-2);root.right.right=newNode(-1);root.left.left.left=newNode(-3);root.right.right.right=newNode(2);Console.WriteLine(spiralSum(root));}}
JavaScript
// JavaScript program to maximum // spiral sum in Binary TreeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionspiralSum(root){if(root===null)return0;letcurrentLevel=[];letnextLevel=[];currentLevel.push(root);// variable to indicate direction // of traversal.letleftToRight=false;// Array to store spiral traversal.letarr=[];while(currentLevel.length>0){letsize=currentLevel.length;while(size-->0){letcurr=currentLevel.pop();arr.push(curr.data);// if current direction to lor, then// push left node first, so that next // level traversal is rol.if(leftToRight){if(curr.left!==null)nextLevel.push(curr.left);if(curr.right!==null)nextLevel.push(curr.right);}else{if(curr.right!==null)nextLevel.push(curr.right);if(curr.left!==null)nextLevel.push(curr.left);}}// Flip the direction.leftToRight=!leftToRight;// Swap the arrays.lettemp=currentLevel;currentLevel=nextLevel;nextLevel=temp;}letans=Number.MIN_SAFE_INTEGER;// variable to store the sum of// current subarray.letprev=0;// Performing kadane's algorithmfor(leti=0;i<arr.length;i++){// If the current subarray sum is less than// 0, then start a new subarray from// index i.if(prev<0)prev=0;// include the current value into // the subarray sum.prev+=arr[i];// Compare the current subarray sum // with the maximum subarray sum.ans=Math.max(ans,prev);}returnans;}// Binary tree// -2// / \// -3 4// / \ / \// 5 1 -2 -1// / \// -3 2letroot=newNode(-2);root.left=newNode(-3);root.right=newNode(4);root.left.left=newNode(5);root.left.right=newNode(1);root.right.left=newNode(-2);root.right.right=newNode(-1);root.left.left.left=newNode(-3);root.right.right.right=newNode(2);console.log(spiralSum(root));
Output
7
Time Complexity: O(n), where n is the number of nodes in the tree. Auxiliary Space: O(n).