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.
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
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:
344 132 435 433 723
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.