Maximum spiral sum in Binary Tree in C++

C++Server Side ProgrammingProgramming

Problem statement

Given a binary tree containing n nodes. The problem 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 next level from left to right, then further next level from right to left and so ons

Example

Consider below tree:
        -2
        / \
     - 3   14
      / \ / \
   50  11 -3 -1
/
-3
Then maximum sum will be 71:
(14 + 50 + 11 + -3 + -1) = 71s

Algorithm

  • Obtain the level order traversal in spiral form of the given binary tree with the help of two stacks and store it in an arrays.
  • Find the maximum sum sub-array of the array so obtained

Example

#include <bits/stdc++.h>
using namespace std;
Node {
   int data;
   Node *left, *right;
};
Node* newNode(int data){
   Node* node = new Node;
   node->data = data;
   node->left = node->right = NULL;
   return node;
}
int maxSum(vector<int> arr, int n) {
   int max_ending_here = INT_MIN;
   int max_so_far = INT_MIN;
   for (int i = 0; i < n; i++) {
      if (max_ending_here < 0) {
         max_ending_here = arr[i];
      } else {
         max_ending_here += arr[i];
      }
      max_so_far = max(max_so_far, max_ending_here);
   }
   return max_so_far;
}
int maxSpiralSum(Node* root){
   if (root == NULL) {
      return 0;
   }
   stack<Node*> s1;
   stack<Node*> s2;
   vector<int> arr;
   s1.push(root);
   while (!s1.empty() || !s2.empty()) {
      while (!s1.empty()) {
         Node* temp = s1.top();
         s1.pop();
         arr.push_back(temp->data);
         if (temp->right) {
            s2.push(temp->right);
         }
         if (temp->left) {
            s2.push(temp->left);
         }
      }
      while (!s2.empty()) {
         Node* temp = s2.top();
         s2.pop();
         arr.push_back(temp->data);
         if (temp->left) {
            s1.push(temp->left);
         }
         if (temp->right) {
            s1.push(temp->right);
         }
      }  
   }
   return maxSum(arr, arr.size());
}
int main(){
   Node* root = newNode(-2);
   root->left = newNode(-3);
   root->right = newNode(14);
   root->left->left = newNode(50);
   root->left->right = newNode(11);
   root->right->left = newNode(-3);
   root->right->right = newNode(-1);
   root->left->left->left = newNode(-3);
   cout << "Maximum Spiral Sum = "
   << maxSpiralSum(root) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Maximum Spiral Sum = 71
raja
Published on 21-Jan-2020 11:36:03
Advertisements