Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order - GeeksforGeeks

16 Jun, 2021
Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1.
Examples: 
Input: K = 0, 
           5
          / \
         3   6
Output:
       3
        \
         5
          \
           6

Input: K = 1,
          2
         / \
        1   3
Output:
     3
      \
       2
        \
         1
Approach: 
The key observation in the problem is that the first node of the skewed tree will be the extreme left or extreme right node of the BST for increasing order and decreasing order respectively.
For Increasing Order we need to do the Inorder Traversal, as the inorder traversal of a BST provides us the increasing sequence of the node values. Hence, the order of traversal at every node will be: Left node: Recurse to its left node if it exists, to get smaller value.Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.Right node: Recurse to the right node if it exists, for larger values.
Left node: Recurse to its left node if it exists, to get smaller value.Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.Right node: Recurse to the right node if it exists, for larger values.
Left node: Recurse to its left node if it exists, to get smaller value.
Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.
Right node: Recurse to the right node if it exists, for larger values.
For Decreasing Order, the order of traversal at every node will be: Right node: Recurse to its right node if it exists, to get larger values.Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.Left node: Recurse to the left node/subtree for smaller values.
Right node: Recurse to its right node if it exists, to get larger values.Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.Left node: Recurse to the left node/subtree for smaller values.
Right node: Recurse to its right node if it exists, to get larger values.
Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.
Left node: Recurse to the left node/subtree for smaller values.
Similarly, by keeping track of the previous node we can traverse the Binary search tree according to the order needed and form the skewed tree.
Below is the implementation of the above approach: 
C++14
Java
Python3
C#
Javascript
// C++ implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing order#include<bits/stdc++.h>using namespace std; // Class of the nodestruct Node{    int val;    Node *left, *right;     Node(int x)    {        val = x;        left = right = NULL;    }}; Node *prevNode = NULL;Node *headNode = NULL; // Function to to flatten the binary// search tree into a skewed tree in// increasing / decreasing ordervoid flattenBTToSkewed(Node *root, int order){         // Base Case    if (!root)        return;     // Condition to check the order    // in which the skewed tree to    // maintained    if (order)        flattenBTToSkewed(root->right, order);    else        flattenBTToSkewed(root->left, order);     Node *rightNode = root->right;    Node *leftNode = root->left;     // Condition to check if the root Node    // of the skewed tree is not defined    if (!headNode)    {        headNode = root;        root->left = NULL;        prevNode = root;    }    else    {        prevNode->right = root;        root->left = NULL;        prevNode = root;    }     // Similarly recurse for the left / right    // subtree on the basis of the order required    if (order)        flattenBTToSkewed(leftNode, order);    else        flattenBTToSkewed(rightNode, order);} // Function to traverse the right// skewed tree using recursionvoid traverseRightSkewed(Node *root){    if (!root)        return;             cout << root->val << " ";    traverseRightSkewed(root->right);} // Driver Codeint main(){         //    5    //     / \    //  3   6    Node *root =new Node(5);    root->left = new Node(3);    root->right = new Node(6);     // Order of the Skewed tree can    // be defined as follows -    // For Increasing order - 0    // For Decreasing order - 1    int order = 0;     flattenBTToSkewed(root, order);     traverseRightSkewed(headNode);} // This code is contributed by mohit kumar 29
// Java implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing orderimport java.io.*; // Class of the nodeclass Node{    int val;    Node left, right;        // Helper function that allocates a new node    // with the given data and NULL left and right    // pointers.    Node(int item)    {        val = item;        left = right = null;    }}class GFG{    public static Node node;    static Node prevNode = null;    static Node headNode = null;       // Function to to flatten the binary    // search tree into a skewed tree in    // increasing / decreasing order    static void flattenBTToSkewed(Node root,                                  int order)    {               // Base Case        if(root == null)        {            return;        }               // Condition to check the order        // in which the skewed tree to        // maintained        if(order > 0)        {            flattenBTToSkewed(root.right, order);        }        else        {            flattenBTToSkewed(root.left, order);        }        Node rightNode = root.right;        Node leftNode = root.left;               // Condition to check if the root Node        // of the skewed tree is not defined        if(headNode == null)        {            headNode = root;            root.left = null;            prevNode = root;        }        else        {            prevNode.right = root;            root.left = null;            prevNode = root;        }               // Similarly recurse for the left / right        // subtree on the basis of the order required        if (order > 0)        {            flattenBTToSkewed(leftNode, order);        }        else        {            flattenBTToSkewed(rightNode, order);        }    }       // Function to traverse the right    // skewed tree using recursion    static void traverseRightSkewed(Node root)    {        if(root == null)        {            return;        }        System.out.print(root.val + " ");        traverseRightSkewed(root.right);           }       // Driver Code    public static void main (String[] args)    {       //    5       //     / \       //  3   6        GFG tree = new GFG();        tree.node = new Node(5);        tree.node.left = new Node(3);        tree.node.right = new Node(6);               // Order of the Skewed tree can        // be defined as follows -        // For Increasing order - 0        // For Decreasing order - 1        int order = 0;        flattenBTToSkewed(node, order);        traverseRightSkewed(headNode);    }} // This code is contributed by avanitrachhadiya2155
# Python3 implementation to flatten# the binary search tree into a skewed# tree in increasing / decreasing order # Class of the nodeclass Node:         # Constructor of node    def __init__(self, val):        self.val = val        self.left = None        self.right = None         prevNode = NoneheadNode = None # Function to to flatten# the binary search tree into a skewed# tree in increasing / decreasing orderdef flattenBTToSkewed(root, order):         # Base Case    if not root:        return         # Condition to check the order    # in which the skewed tree to maintained    if order:        flattenBTToSkewed(root.right, order)    else:        flattenBTToSkewed(root.left, order)             global headNode; global prevNode    rightNode = root.right    leftNode = root.left         # Condition to check if the root Node    # of the skewed tree is not defined    if not headNode:        headNode = root        root.left = None        prevNode = root    else:        prevNode.right = root        root.left = None        prevNode = root         # Similarly recurse for the left / right    # subtree on the basis of the order required    if order:        flattenBTToSkewed(leftNode, order)    else:        flattenBTToSkewed(rightNode, order) # Function to traverse the right# skewed tree using recursiondef traverseRightSkewed(root):    if not root:        return    print(root.val, end = " ")    traverseRightSkewed(root.right) # Driver Codeif __name__ == "__main__":    # 5    #      / \    # 3   6    root = Node(5)    root.left = Node(3)    root.right = Node(6)         prevNode = None    headNode = None         # Order of the Skewed tree can    # be defined as follows -    # For Increasing order - 0    # For Decreasing order - 1    order = 0         flattenBTToSkewed(root, order)         traverseRightSkewed(headNode)
// C# implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing orderusing System; // Class of the nodeclass Node{    public int val;    public Node left, right;         // Helper function that allocates a new    // node with the given data and NULL    // left and right pointers.    public Node(int item)    {        val = item;        left = right = null;    }} class GFG{     public static Node node;static Node prevNode = null;static Node headNode = null; // Function to to flatten the binary// search tree into a skewed tree in// increasing / decreasing orderstatic void flattenBTToSkewed(Node root, int order){         // Base Case    if (root == null)    {        return;    }         // Condition to check the order    // in which the skewed tree to    // maintained    if (order > 0)    {        flattenBTToSkewed(root.right, order);    }    else    {        flattenBTToSkewed(root.left, order);    }    Node rightNode = root.right;    Node leftNode = root.left;        // Condition to check if the root Node    // of the skewed tree is not defined    if (headNode == null)    {        headNode = root;        root.left = null;        prevNode = root;    }    else    {        prevNode.right = root;        root.left = null;        prevNode = root;    }        // Similarly recurse for the left / right    // subtree on the basis of the order required    if (order > 0)    {        flattenBTToSkewed(leftNode, order);    }    else    {        flattenBTToSkewed(rightNode, order);    }} // Function to traverse the right// skewed tree using recursionstatic void traverseRightSkewed(Node root){    if (root == null)    {        return;    }    Console.Write(root.val + " ");    traverseRightSkewed(root.right);} // Driver Codestatic public void Main(){         //      5    //     / \    //    3   6    GFG.node = new Node(5);    GFG.node.left = new Node(3);    GFG.node.right = new Node(6);         // Order of the Skewed tree can    // be defined as follows -    // For Increasing order - 0    // For Decreasing order - 1    int order = 0;         flattenBTToSkewed(node, order);    traverseRightSkewed(headNode);}} // This code is contributed by rag2127
<script>// Javascript implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing order // Class of the nodeclass Node{    // Helper function that allocates a new node    // with the given data and NULL left and right    // pointers.    constructor(item)    {        this.val = item;        this.left = this.right = null;    }} let node;let prevNode = null;let headNode = null; // Function to to flatten the binary    // search tree into a skewed tree in    // increasing / decreasing orderfunction flattenBTToSkewed(root,order){    // Base Case        if(root == null)        {            return;        }                // Condition to check the order        // in which the skewed tree to        // maintained        if(order > 0)        {            flattenBTToSkewed(root.right, order);        }        else        {            flattenBTToSkewed(root.left, order);        }        let rightNode = root.right;        let leftNode = root.left;                // Condition to check if the root Node        // of the skewed tree is not defined        if(headNode == null)        {            headNode = root;            root.left = null;            prevNode = root;        }        else        {            prevNode.right = root;            root.left = null;            prevNode = root;        }                // Similarly recurse for the left / right        // subtree on the basis of the order required        if (order > 0)        {            flattenBTToSkewed(leftNode, order);        }        else        {            flattenBTToSkewed(rightNode, order);        }} // Function to traverse the right    // skewed tree using recursionfunction traverseRightSkewed(root){    if(root == null)        {            return;        }        document.write(root.val + " ");        traverseRightSkewed(root.right);   } // Driver Code //    5       //     / \       //  3   6node = new Node(5);node.left = new Node(3);node.right = new Node(6); // Order of the Skewed tree can// be defined as follows -// For Increasing order - 0// For Decreasing order - 1let order = 0;flattenBTToSkewed(node, order);traverseRightSkewed(headNode); // This code is contributed by unknown2108</script>
3 5 6
 
mohit kumar 29
avanitrachhadiya2155
rag2127
unknown2108
Binary Search Tree
Recursion
Tree
Recursion
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Red Black Tree vs AVL Tree
Construct BST from given preorder traversal | Set 2
Print BST keys in the given range
Find median of BST in O(n) time and O(1) space
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction