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
Program to find out if a BST is present in a given binary tree in Python
A Binary Search Tree (BST) is a special type of binary tree where the left subtree contains values less than or equal to the root, and the right subtree contains values greater than or equal to the root. This problem asks us to find the largest BST subtree within a given binary tree.
Algorithm Approach
The algorithm uses a recursive approach to find the largest BST subtree ?
- For each node, check if it forms a valid BST with its subtrees
- A node forms a BST if: left child ? node ? right child
- Count the size of each valid BST subtree
- Track the largest BST found so far
Implementation
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert(root, data):
queue = [root]
while queue:
node = queue.pop(0)
if not node.left:
if data is not None:
node.left = TreeNode(data)
else:
node.left = TreeNode(0)
break
else:
queue.append(node.left)
if not node.right:
if data is not None:
node.right = TreeNode(data)
else:
node.right = TreeNode(0)
break
else:
queue.append(node.right)
def make_tree(elements):
if not elements:
return None
root = TreeNode(elements[0])
for element in elements[1:]:
insert(root, element)
return root
def print_tree(root):
if root is not None:
print_tree(root.left)
print(root.val, end=', ')
print_tree(root.right)
def find_largest_bst(root):
max_size = 0
largest_bst_root = None
def recurse(node):
nonlocal max_size, largest_bst_root
if not node:
return 0
# Get sizes of left and right subtrees
left_size = recurse(node.left)
right_size = recurse(node.right)
# Check if current node forms a valid BST
current_size = -float("inf")
left_valid = (node.left is None or node.left.val <= node.val)
right_valid = (node.right is None or node.val <= node.right.val)
if left_valid and right_valid:
current_size = left_size + right_size + 1
# Update largest BST if current is larger
if current_size > max_size:
max_size = current_size
largest_bst_root = node
return current_size if current_size > 0 else 0
recurse(root)
return largest_bst_root
# Create the binary tree: [1, 4, 6, 3, 5]
tree = make_tree([1, 4, 6, 3, 5])
print("Original tree (in-order traversal):")
print_tree(tree)
print()
print("Largest BST subtree (in-order traversal):")
largest_bst = find_largest_bst(tree)
print_tree(largest_bst)
Original tree (in-order traversal): 3, 4, 5, 1, 6, Largest BST subtree (in-order traversal): 3, 4, 5,
How It Works
The algorithm traverses each node and validates the BST property ?
- Base case: Empty nodes return size 0
- Recursive calls: Get sizes of left and right subtrees
- BST validation: Check if left ? root ? right
- Size calculation: If valid BST, size = left_size + right_size + 1
- Update maximum: Track the largest valid BST found
Key Points
- Time complexity: O(n) where n is the number of nodes
- Space complexity: O(h) where h is the height of the tree
- The algorithm finds the subtree with maximum BST nodes
- Returns the root node of the largest BST subtree
Conclusion
This solution efficiently finds the largest BST subtree using a bottom-up recursive approach. It validates the BST property at each node and tracks the maximum valid subtree size, returning the root of the largest BST found.
Advertisements
