VOOZH about

URL: https://www.geeksforgeeks.org/dsa/create-a-wave-array-from-the-given-binary-search-tree/

⇱ Create a wave array from the given Binary Search Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create a wave array from the given Binary Search Tree

Last Updated : 23 Jul, 2025

Given a Binary Search Tree, the task is to create a wave array from the given Binary Search Tree. An array arr[0..n-1] is called a wave array if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ...

Examples:

Input:

👁 Image


Output: 4 2 8 6 12 10 14
Explanation: The above mentioned array {4, 2, 8, 6, 12, 10, 14} is one of the many valid wave arrays.

Input:

👁 Image

Output: 4 2 8 6 12 

Approach: The given problem can be solved by the observation that the Inorder Traversal of the Binary Search Tree gives nodes in non-decreasing order. Therefore, store the inorder traversal of the given tree into a vector. Since the vector contains elements in sorted order, it can be converted into a wave array by swapping the adjacent elements for all elements in the range [0, N) using the approach discussed in this article.

Below is the implementation of the above approach:


Output: 
4 2 8 6 12 10 14

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment