![]() |
Given a Binary Search Tree consisting of N distinct nodes, the task is to flatten the given Binary Search Tree to convert the tree into a wave list. A wave list arr[0..n-1] is called a wave list if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= … . Examples:
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 of the first N/2 and the last N/2 nodes using the iterative Inorder traversal of the tree and reverse of the inorder traversal of the tree in two stacks S1 and S2 respectively and the right pointer of nodes in the stack to get the Wave List. After these steps, make all the left pointers of the tree NULL to make it flatten. Below is the implementation of the above approach: C++
Java
Python3
C#
Javascript
Output:
0 10 1
Time Complexity: O(N) |
Reffered: https://www.geeksforgeeks.org
Binary Search Tree |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |