Create a wave array from the given Binary Search Tree

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[3] = …Examples:Input: Output: 4 2 8 6 12 10 14Explanation: The above mentioned array {4, 2, 8, 6, 12, 10, 14} is one of the many valid wave arrays.Input: 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:C++#include using namespace std;  struct Node {    int data;    Node* right;    Node* left;          Node(int data)    {        this->data = data;        this->left = NULL;        this->right = NULL;    }};  void toWaveArray(Node* root){        vector waveArr;      stack s;    Node* curr = root;              while (curr != NULL || s.empty() == false) {                          while (curr != NULL) {                                                  s.push(curr);            curr = curr->left;        }        curr = s.top();        s.pop();                  waveArr.push_back(curr->data);                  curr = curr->right;    }          for (int i = 0;         i + 1 < waveArr.size(); i += 2) {        swap(waveArr[i], waveArr[i + 1]);    }          for (int i = 0; i < waveArr.size(); i++) {        cout right = new Node(12);    root->right->left = new Node(10);    root->right->right = new Node(14);    root->left->left = new Node(2);    root->left->right = new Node(6);      toWaveArray(root);      return 0;}Output:
4 2 8 6 12 10 14
Time Complexity: O(N)Auxiliary Space: O(N)Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.