08. Binary Tree to BST
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
I solved this problem by utilizing the BST property, where the inorder traversal of the tree results in sorted values. In this context, I reversed this process by:
First obtaining the inorder order of the binary tree.
Sorting the values of the binary tree.
Subsequently updating the binary tree with the sorted values.
Here are the steps to do so:
Conduct an in-order traversal of the binary tree to obtain the nodes in inorder order.
Store these nodes in a nodes
vector and also collect the binary tree values in a values
vector.
Sort the values
vector to arrange the values in ascending order.
Assign these sorted values
to the corresponding nodes
in the vector.
Time Complexity: O(NlogN)
(due to sorting), where N is the number of nodes in the binary tree.
Auxiliary Space Complexity: O(N)
(for the vector to store nodes).
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the repository.