Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of decimal equivalents of binary node values in each level of a Binary Tree
Next article icon

Convert a Binary Tree to BST by left shifting digits of node values

Last Updated : 18 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree of positive integers. The task is to convert it to a BST using left shift operations on the digits of the nodes. If it is not possible to convert the binary tree to BST then print -1.

Examples:

Input:                      443 
                              /        \  
                          132      543 
                                    /      \ 
                                343     237

Output:                   344 
                               /        \ 
                         132       435 
                                   /        \ 
                               433       723

Explanation:   443 ? left shift two times ? 344 
                         132 ? zero shift operations ? 132 
                         543 ? left shift one time ? 435 
                         343 ? left shift one time ? 433 
                         237 ? left shift two times ? 723

Input:                    43 
                         /        \ 
                      56         45

Output: -1

Approach: The idea is to perform Inorder traversal on the Binary Tree in increasing order because in-order traversal of a BST always generates sorted sequence. Follow the steps below to solve the problem:

  • Initialize a variable, say prev = -1, to keep track of the value of the previous node.
  • Then, traverse the tree using Inorder Traversal and try to convert every node to its lowest possible value greater than the previous value by left shifting its digits.
  • After performing these operations, check if the binary tree is a BST or not.
  • If found to be true, print the tree. Otherwise, print -1.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Structure of a Node struct TreeNode {    int val;    TreeNode *left, *right;      TreeNode(int key)     {         val = key;         left = NULL;         right = NULL;     } };  // Function to check if // the tree is BST or not bool isBST(TreeNode *root, TreeNode *l = NULL, TreeNode *r = NULL) {      // Base condition     if (!root)         return true;      // Check for left child     if (l && root->val <= l->val)         return false;      // Check for right child     if (r && root->val >= r->val)         return false;      // Check for left and right subtrees     return isBST(root->left, l, root) and isBST(root->right, root, r); }  // Function to convert a tree to BST // by left shift of its digits void ConvTree(TreeNode *root,int &prev) {      // If root is NULL     if (!root)         return;      // Recursively modify the     // left subtree     ConvTree(root->left,prev);      // Initialise optimal element     // to the initial element     int optEle = root->val;      // Convert it into a string     string strEle = to_string(root->val);      // For checking all the     // left shift operations     bool flag = true;     for (int idx = 0; idx < strEle.size(); idx++)     {          // Perform left shift         int shiftedNum = stoi(strEle.substr(idx) + strEle.substr(0, idx));          // If the number after left shift         // is the minimum and greater than         // its previous element          // first value >= prev          // used to setup initialize optEle         // cout<<prev<<endl;         if (shiftedNum >= prev and flag)         {             optEle = shiftedNum;             flag = false;           }          if (shiftedNum >= prev)             optEle = min(optEle, shiftedNum);       }     root->val = optEle;     prev = root->val;        // Recursively solve for right     // subtree     ConvTree(root->right,prev); }  // Function to print level // order traversal of a tree void levelOrder(TreeNode *root) {     queue<TreeNode*> que;     que.push(root);     while(true)     {         int length = que.size();         if (length == 0)             break;         while (length)         {             auto temp = que.front();             que.pop();             cout << temp->val << " ";             if (temp->left)                 que.push(temp->left);             if (temp->right)                 que.push(temp->right);             length -= 1;           }           cout << endl;         }            // new line         cout << endl; }  // Driver Code int main() {    TreeNode *root = new TreeNode(443);   root->left = new TreeNode(132);   root->right = new TreeNode(543);   root->right->left = new TreeNode(343);   root->right->right = new TreeNode(237);    // Converts the tree to BST   int prev = -1;   ConvTree(root, prev);    // If tree is converted to a BST   if (isBST(root, NULL, NULL))   {       // Print its level order traversal       levelOrder(root);     }   else   {            // not possible       cout << (-1);     } }  // This code is contributed by mohit kumar 29 
Java
// Java program for the above approach import java.util.*;  class GFG{      static int prev;  // Structure of a Node static class TreeNode {     int val;     TreeNode left, right;          TreeNode(int key)     {         val = key;         left = null;         right = null;     } };  // Function to check if // the tree is BST or not static boolean isBST(TreeNode root, TreeNode l,                       TreeNode r) {          // Base condition     if (root == null)         return true;      // Check for left child     if (l != null && root.val <= l.val)         return false;      // Check for right child     if (r != null && root.val >= r.val)         return false;      // Check for left and right subtrees     return isBST(root.left, l, root) &             isBST(root.right, root, r); }  // Function to convert a tree to BST // by left shift of its digits static void ConvTree(TreeNode root) {          // If root is null     if (root == null)         return;              // Recursively modify the     // left subtree     ConvTree(root.left);      // Initialise optimal element     // to the initial element     int optEle = root.val;      // Convert it into a String     String strEle = String.valueOf(root.val);      // For checking all the     // left shift operations     boolean flag = true;          for(int idx = 0; idx < strEle.length(); idx++)     {                  // Perform left shift         int shiftedNum = Integer.parseInt(             strEle.substring(idx) +              strEle.substring(0, idx));          // If the number after left shift         // is the minimum and greater than         // its previous element          // first value >= prev          // used to setup initialize optEle         // System.out.print(prev<<endl;         if (shiftedNum >= prev && flag)         {             optEle = shiftedNum;             flag = false;         }                  if (shiftedNum >= prev)             optEle = Math.min(optEle, shiftedNum);     }     root.val = optEle;     prev = root.val;        // Recursively solve for right     // subtree     ConvTree(root.right); }  // Function to print level // order traversal of a tree static void levelOrder(TreeNode root) {     Queue<TreeNode> que = new LinkedList<GFG.TreeNode>();     que.add(root);          while(true)     {         int length = que.size();                  if (length == 0)             break;                      while (length > 0)         {             TreeNode temp = que.peek();             que.remove();             System.out.print(temp.val + " ");                          if (temp.left != null)                 que.add(temp.left);             if (temp.right != null)                 que.add(temp.right);                              length -= 1;         }         System.out.println();     }          // New line     System.out.println(); }  // Driver Code public static void main(String[] args) {     TreeNode root = new TreeNode(443);     root.left = new TreeNode(132);     root.right = new TreeNode(543);     root.right.left = new TreeNode(343);     root.right.right = new TreeNode(237);          // Converts the tree to BST     prev = -1;     ConvTree(root);          // If tree is converted to a BST     if (isBST(root, null, null))     {                  // Print its level order traversal         levelOrder(root);     }     else     {                  // not possible         System.out.print(-1);     } } }  // This code is contributed by shikhasingrajput  
Python3
# Python3 program for the above approach  # Structure of a Node class TreeNode:     def __init__(self, key):         self.val = key         self.left = None         self.right = None  # Function to check if # the tree is BST or not def isBST(root, l = None, r = None):      # Base condition     if not root:         return True      # Check for left child     if l and root.val <= l.val:         return False      # Check for right child     if r and root.val >= r.val:         return False      # Check for left and right subtrees     return isBST(root.left, l, root) and isBST(root.right, root, r)  # Function to convert a tree to BST # by left shift of its digits def ConvTree(root):     global prev      # If root is NULL     if not root:         return      # Recursively modify the     # left subtree     ConvTree(root.left)      # Initialise optimal element     # to the initial element     optEle = root.val      # Convert it into a string     strEle = str(root.val)      # For checking all the     # left shift operations     flag = True      for idx in range(len(strEle)):          # Perform left shift         shiftedNum = int(strEle[idx:] + strEle[:idx])          # If the number after left shift         # is the minimum and greater than         # its previous element          # first value >= prev          # used to setup initialize optEle         if shiftedNum >= prev and flag:             optEle = shiftedNum             flag = False          if shiftedNum >= prev:             optEle = min(optEle, shiftedNum)      root.val = optEle     prev = root.val     # Recursively solve for right     # subtree     ConvTree(root.right)  # Function to print level # order traversal of a tree def levelOrder(root):     que = [root]     while True:         length = len(que)         if not length:             break          while length:             temp = que.pop(0)             print(temp.val, end =' ')             if temp.left:                 que.append(temp.left)             if temp.right:                 que.append(temp.right)             length -= 1         # new line         print()  # Driver Code  root = TreeNode(443) root.left = TreeNode(132) root.right = TreeNode(543) root.right.left = TreeNode(343) root.right.right = TreeNode(237)  # Initialize to # previous element prev = -1  # Converts the tree to BST ConvTree(root)  # If tree is converted to a BST if isBST(root, None, None):      # Print its level order traversal     levelOrder(root) else:     # not possible     print(-1) 
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG {      static int prev;  // Structure of a Node class TreeNode {     public int val;     public TreeNode left, right;       public TreeNode(int key)     {         val = key;         left = null;         right = null;     } };  // Function to check if // the tree is BST or not static bool isBST(TreeNode root, TreeNode l,                       TreeNode r) {          // Base condition     if (root == null)         return true;      // Check for left child     if (l != null && root.val <= l.val)         return false;      // Check for right child     if (r != null && root.val >= r.val)         return false;      // Check for left and right subtrees     return isBST(root.left, l, root) &             isBST(root.right, root, r); }  // Function to convert a tree to BST // by left shift of its digits static void ConvTree(TreeNode root) {          // If root is null     if (root == null)         return;              // Recursively modify the     // left subtree     ConvTree(root.left);      // Initialise optimal element     // to the initial element     int optEle = root.val;      // Convert it into a String     String strEle = String.Join("", root.val);      // For checking all the     // left shift operations     bool flag = true;          for(int idx = 0; idx < strEle.Length; idx++)     {                  // Perform left shift         int shiftedNum = Int32.Parse(             strEle.Substring(idx) +              strEle.Substring(0, idx));          // If the number after left shift         // is the minimum and greater than         // its previous element          // first value >= prev          // used to setup initialize optEle         // Console.Write(prev<<endl;         if (shiftedNum >= prev && flag)         {             optEle = shiftedNum;             flag = false;         }                  if (shiftedNum >= prev)             optEle = Math.Min(optEle, shiftedNum);     }     root.val = optEle;     prev = root.val;        // Recursively solve for right     // subtree     ConvTree(root.right); }  // Function to print level // order traversal of a tree static void levelOrder(TreeNode root) {     Queue<TreeNode> que = new Queue<GFG.TreeNode>();     que.Enqueue(root);          while(true)     {         int length = que.Count;          if (length == 0)             break;               while (length > 0)         {             TreeNode temp = que.Peek();             que.Dequeue();             Console.Write(temp.val + " ");                    if (temp.left != null)                 que.Enqueue(temp.left);             if (temp.right != null)                 que.Enqueue(temp.right);                     length -= 1;         }         Console.WriteLine();     }          // New line     Console.WriteLine(); }  // Driver Code public static void Main(String[] args) {     TreeNode root = new TreeNode(443);     root.left = new TreeNode(132);     root.right = new TreeNode(543);     root.right.left = new TreeNode(343);     root.right.right = new TreeNode(237);          // Converts the tree to BST     prev = -1;     ConvTree(root);          // If tree is converted to a BST     if (isBST(root, null, null))     {                  // Print its level order traversal         levelOrder(root);     }     else     {                  // not possible         Console.Write(-1);     } } }   // This code is contributed by shikhasingrajput  
JavaScript
<script>    // JavaScript program for the above approach      let prev;     // Structure of a Node   class TreeNode   {       constructor(key) {          this.left = null;          this.right = null;          this.val = key;       }   }      // Function to check if   // the tree is BST or not   function isBST(root, l, r)   {               // Base condition       if (root == null)           return true;           // Check for left child       if (l != null && root.val <= l.val)           return false;           // Check for right child       if (r != null && root.val >= r.val)           return false;           // Check for left and right subtrees       return isBST(root.left, l, root) &              isBST(root.right, root, r);   }       // Function to convert a tree to BST   // by left shift of its digits   function ConvTree(root)   {               // If root is null       if (root == null)           return;                   // Recursively modify the       // left subtree       ConvTree(root.left);           // Initialise optimal element       // to the initial element       let optEle = root.val;           // Convert it into a String       let strEle = (root.val).toString();           // For checking all the       // left shift operations       let flag = true;               for(let idx = 0; idx < strEle.length; idx++)       {                       // Perform left shift           let shiftedNum = parseInt(               strEle.substring(idx) +               strEle.substring(0, idx));               // If the number after left shift           // is the minimum and greater than           // its previous element               // first value >= prev               // used to setup initialize optEle           // Console.Write(prev<<endl;           if (shiftedNum >= prev && flag)           {               optEle = shiftedNum;               flag = false;           }                       if (shiftedNum >= prev)               optEle = Math.min(optEle, shiftedNum);       }       root.val = optEle;       prev = root.val;             // Recursively solve for right       // subtree       ConvTree(root.right);   }       // Function to print level   // order traversal of a tree   function levelOrder(root)   {       let que = [];       que.push(root);               while(true)       {           let length = que.length;           if (length == 0)               break;                while (length > 0)           {               let temp = que[0];               que.shift();               document.write(temp.val + " ");                     if (temp.left != null)                   que.push(temp.left);               if (temp.right != null)                   que.push(temp.right);                      length -= 1;           }           document.write("</br>");       }               // New line       document.write("</br>");   }      let root = new TreeNode(443);   root.left = new TreeNode(132);   root.right = new TreeNode(543);   root.right.left = new TreeNode(343);   root.right.right = new TreeNode(237);       // Converts the tree to BST   prev = -1;   ConvTree(root);       // If tree is converted to a BST   if (isBST(root, null, null))   {               // Print its level order traversal       levelOrder(root);   }   else   {               // not possible       document.write(-1);   }      </script> 

Output: 
344  132 435  433 723

 

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


Next Article
Sum of decimal equivalents of binary node values in each level of a Binary Tree
author
rohitsingh07052
Improve
Article Tags :
  • Tree
  • Mathematical
  • Binary Search Tree
  • DSA
  • tree-level-order
Practice Tags :
  • Binary Search Tree
  • Mathematical
  • Tree

Similar Reads

  • Convert Binary Tree to Doubly Linked List by keeping track of visited node
    Given a Binary Tree, The task is to convert it to a Doubly Linked List keeping the same order.  The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The fir
    15+ min read
  • Construct XOR tree by Given leaf nodes of Perfect Binary Tree
    Given the leaf nodes of a perfect binary tree, the task is to construct the XOR tree and print the root node of this tree. An XOR tree is a tree whose parent node is the XOR of the left child and the right child node of the tree. Parent node = Left child node ^ Right child node Examples: Input: arr
    12 min read
  • Convert Binary Tree to Doubly Linked List by fixing left and right pointers
    Given a Binary Tree, the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node of In
    10 min read
  • How to insert a node in Binary Search Tree using Iteration
    You are given a binary search tree (BST) and a value to insert into the tree. Print inorder traversal of the BST after the insertion.Example: Input:To the given BST insert 40 Output: Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searchin
    10 min read
  • Sum of decimal equivalents of binary node values in each level of a Binary Tree
    Given a Binary Tree consisting of nodes with values 0 and 1 only, the task is to find the total sum of the decimal equivalents of the binary numbers formed by connecting nodes at the same level from left to right, on each level. Examples: Input: Below is the given Tree: 0 / \ 1 0 / \ / \ 0 1 1 1Outp
    15 min read
  • Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes
    Given a Binary Tree, the task is to convert the given Binary Tree to the Symmetric Tree by adding the minimum number of nodes in the given Tree. Examples: Input: Output: Input: Output: Approach: To solve this problem, follow the below steps: Make a function buildSymmetricTree which will accept two p
    8 min read
  • Count Non-Leaf nodes in a Binary Tree
    Given a Binary tree, count the total number of non-leaf nodes in the tree Examples: Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
    10 min read
  • Find height of a special binary tree whose leaf nodes are connected
    Given a special binary tree whose leaf nodes are connected to form a circular doubly linked list, the task is to find the height of the tree. Examples: Input: Output: 2Explanation: The height of binary tree after recognizing the leaf nodes is 2. In the above binary tree, 6, 5 and 4 are leaf nodes an
    10 min read
  • Count of subtrees in a Binary Tree having bitwise OR value K
    Given a value K and a binary tree, the task is to find out the number of subtrees having bitwise OR of all its elements equal to K. Examples: Input: K = 5, Tree = 2 / \ 1 1 / \ \ 10 5 4 Output: 2 Explanation: Subtree 1: 5 It has only one element i.e. 5. So bitwise OR of subtree = 5 Subtree 2: 1 \ 4
    8 min read
  • Left rotate digits of node values of all levels of a Binary Tree in increasing order
    Given a Binary Tree, the task is to modify the Tree by left rotating every node any number of times such that every level consists of node values in increasing order from left to right. If it is not possible to arrange node values of any level in increasing order, then print "-1". Examples: Input: 3
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences