import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
static void inorder(BinaryTreeNode<Integer> root, List<Integer> ans) {
if (root == null) {
return;
}
inorder(root.left, ans);
ans.add(root.data);
inorder(root.right, ans);
}
static void solve(BinaryTreeNode<Integer> root, List<Integer> ans, int[] index) {
if (root == null) {
return;
}
solve(root.left, ans, index);
root.data = ans.get(index[0]++);
solve(root.right, ans, index);
}
static BinaryTreeNode<Integer> binaryTreeToBst(BinaryTreeNode<Integer> root) {
List<Integer> ans = new ArrayList<>();
inorder(root, ans);
Collections.sort(ans);
int[] index = {0};
solve(root, ans, index);
return root;
}
public static void main(String[] args) {
BinaryTreeNode<Integer> root = new BinaryTreeNode<>(4);
root.left = new BinaryTreeNode<>(2);
root.right = new BinaryTreeNode<>(7);
root.left.left = new BinaryTreeNode<>(1);
root.left.right = new BinaryTreeNode<>(3);
BinaryTreeNode<Integer> bstRoot = binaryTreeToBst(root);
// Printing the elements of the BST in inorder traversal
printInorder(bstRoot);
}
static void printInorder(BinaryTreeNode<Integer> root) {
if (root != null) {
printInorder(root.left);
System.out.print(root.data + " ");
printInorder(root.right);
}
}
}