Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check if a triplet with given sum exists in BST in Python
In this problem, we need to find if there exists any triplet (group of three elements) in a Binary Search Tree (BST) that sums up to a given target value. We'll use the BST's inorder traversal property to get a sorted array, then apply the two-pointer technique.
Approach
The solution involves two main steps:
- Perform inorder traversal of BST to get elements in sorted order
- Use three pointers to find triplet with target sum
BST Structure
Implementation
class TreeNode:
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def traverse_inorder(tree_root, inorder):
if tree_root is None:
return
traverse_inorder(tree_root.left, inorder)
inorder.append(tree_root.value)
traverse_inorder(tree_root.right, inorder)
def solve(tree_root, target_sum):
# Get sorted array from BST using inorder traversal
sorted_values = []
traverse_inorder(tree_root, sorted_values)
# Find triplet using three pointers
n = len(sorted_values)
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
current_sum = sorted_values[i] + sorted_values[left] + sorted_values[right]
if current_sum == target_sum:
return True
elif current_sum < target_sum:
left += 1
else:
right -= 1
return False
# Create the BST
tree_root = TreeNode(5)
tree_root.left = TreeNode(3)
tree_root.right = TreeNode(7)
tree_root.left.left = TreeNode(2)
tree_root.left.right = TreeNode(4)
tree_root.right.left = TreeNode(6)
tree_root.right.right = TreeNode(8)
# Test with target sum = 12
result = solve(tree_root, 12)
print(f"Triplet with sum 12 exists: {result}")
# Show the sorted array from inorder traversal
sorted_values = []
traverse_inorder(tree_root, sorted_values)
print(f"Sorted values from BST: {sorted_values}")
Triplet with sum 12 exists: True Sorted values from BST: [2, 3, 4, 5, 6, 7, 8]
How It Works
The algorithm works in two phases ?
- Inorder Traversal: Extracts elements from BST in sorted order [2, 3, 4, 5, 6, 7, 8]
- Three Pointer Technique: For each element as the first of triplet, use two pointers to find the other two elements
For target sum 12, we find triplet (2, 4, 6) where 2 + 4 + 6 = 12.
Testing Different Cases
# Test multiple target sums
test_cases = [12, 15, 10, 25]
for target in test_cases:
result = solve(tree_root, target)
print(f"Target sum {target}: {'Found' if result else 'Not found'}")
Target sum 12: Found Target sum 15: Found Target sum 10: Found Target sum 25: Not found
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n²) | O(n) for traversal + O(n²) for finding triplet |
| Space | O(n) | Array to store inorder traversal |
Conclusion
This solution efficiently finds triplets in a BST by leveraging the sorted property from inorder traversal. The two-pointer technique reduces the search complexity for each triplet combination.
Advertisements
