VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-spiral-sum-in-binary-tree/

⇱ Maximum spiral sum in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum spiral sum in Binary Tree

Last Updated : 22 Oct, 2024

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:

👁 maximum-spiral-sum-in-binary-tree-1

Output: 7
Explanation: Maximum spiral sum = 4 + (-1) + (-2) + 1 + 5 = 7

👁 7

Approach:

The idea is to obtain the level order traversal in spiral form of the given binary tree with the help of two stacks and store it in an array. Find the maximum sum sub-array of the array so obtained.

Below is the implementation of the above approach:


Output
7

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n).

Comment
Article Tags:
Article Tags: