You are given a Binary Search Tree (BST), and the task is to flatten it into a sorted single linked list. The linked list is implemented using the left pointers of the original BST nodes, while the right pointers of all nodes should be set to null.
Input: root =[4,2,5,1,3]Output: [1,2,3,4,5]Explanation: The BST nodes are traversed inin-order order to produce the sorted linked list. Each node's left points to the next node in the list, and right is set to null.
classSolution {
private TreeNode prev =null; // Keeps track of the previous nodeprivate TreeNode head =null; // Head of the linked listpublic TreeNode flattenBST(TreeNode root) {
// Perform in-order traversal on the BST inOrder(root);
return head;
}
privatevoidinOrder(TreeNode node) {
if (node ==null) return;
// Traverse the left subtree inOrder(node.left);
// Process the current nodeif (prev ==null) {
head = node; // If there's no previous node, establish head } else {
prev.left= node; // Rewire `left` pointer of prev node }
node.right=null; // Set the current node's right pointer to null prev = node; // Update prev to be the current node// Traverse the right subtree inOrder(node.right);
}
}
classSolution:
def __init__(self):
self.prev =None# Keeps track of the previous node self.head =None# Head of the linked listdefflattenBST(self, root):
# Perform in-order traversal on the BST self.inOrder(root)
return self.head
definOrder(self, node):
ifnot node:
return# Traverse the left subtree self.inOrder(node.left)
# Process the current nodeifnot self.prev:
self.head = node # If there's no previous node, establish headelse:
self.prev.left = node # Rewire `left` pointer of prev node node.right =None# Set the current node's right pointer to null self.prev = node # Update prev to be the current node# Traverse the right subtree self.inOrder(node.right)