For each node in a binary search tree, create a duplicate of the node, and insert the duplicate as the left child of the original node. The updated tree should preserve its binary search property.
Input:
2/ \
13 Output:
2/ \
23//13/1Explanation:
Each node is duplicated as the left child:
- Node `2` gets a duplicate left child `2`.- Node `1` gets a duplicate left child `1`.- Node `3` gets a duplicate left child `3`.
Input:
10/\520Output:
10/\1020//520/5Explanation:
Each node is duplicated as the left child:- Node `10` gets a duplicate left child `10`.- Node `5` gets a duplicate left child `5`.- Node `20` gets a duplicate left child `20`.
The problem is exactly as described — for each node, a duplicate needs to be created and inserted as the left child. Importantly, the binary search tree property is maintained since the duplicate nodes appear as left children without disrupting the order of left (smaller values) and right (greater values) descendants.
classSolution:
defduplicateTree(self, root):
if root isNone:
return# Create duplicate node duplicate = TreeNode(root.val)
# Attach duplicate as the left child duplicate.left = root.left
root.left = duplicate
# Recursive calls for original left and right children self.duplicateTree(duplicate.left)
self.duplicateTree(root.right)
defprintTree(self, root):
# Helper function to print the tree (inorder traversal)if root isNone:
return self.printTree(root.left)
print(root.val, end=" ")
self.printTree(root.right)
# Driver codeif __name__ =="__main__":
solution = Solution()
# Example tree root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)
print("Original Tree:")
solution.printTree(root)
# Transform the tree solution.duplicateTree(root)
print("\nTransformed Tree:")
solution.printTree(root)