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
Program to find largest binary search subtree from a given tree in Python
A binary tree may contain subtrees that are valid binary search trees (BST). We need to find the largest subtree (with maximum number of nodes) that forms a valid BST from the given binary tree.
So, if the input is like ?
Then the output will be the subtree with nodes [4, 5, 6] as it forms the largest valid BST ?
Algorithm Steps
To solve this, we will follow these steps ?
- Initialize
max_sizeandmax_nodeas lists to track the largest BST found - Define a recursive function
traverse()that processes each node - For each node, get inorder traversal of left and right subtrees
- Combine left subtree + current node + right subtree into a list
- Check if the combined list is sorted (indicates a valid BST)
- If valid and larger than current maximum, update the result
- Return the combined list for parent nodes to use
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.val = data
self.left = left
self.right = right
def print_tree(root):
if root is not None:
print_tree(root.left)
print(root.val, end=', ')
print_tree(root.right)
class Solution:
def solve(self, root):
max_size = [0]
max_node = [None]
def traverse(node):
if not node:
return []
left = traverse(node.left)
right = traverse(node.right)
lst = left + [node.val] + right
if sorted(lst) == lst:
if max_size[0] < len(lst):
max_size[0] = len(lst)
max_node[0] = node
return lst
traverse(root)
return max_node[0]
# Create the binary tree
ob = Solution()
root = TreeNode(12)
root.left = TreeNode(3)
root.right = TreeNode(5)
root.right.left = TreeNode(4)
root.right.right = TreeNode(6)
# Find and print the largest BST subtree
result = ob.solve(root)
print_tree(result)
4, 5, 6,
How It Works
The algorithm performs an inorder traversal of each subtree and checks if the resulting sequence is sorted. For the example tree:
- Node 12 subtree: [3, 12, 4, 5, 6] − not sorted, so not a BST
- Node 5 subtree: [4, 5, 6] − sorted, so it's a valid BST with 3 nodes
- Individual nodes: Each single node is a BST with 1 node
The subtree rooted at node 5 with values [4, 5, 6] is the largest valid BST with 3 nodes.
Time Complexity
The time complexity is O(n²) in the worst case, where n is the number of nodes. This is because for each node, we might need to sort the combined list, and sorting takes O(k log k) time where k is the size of the subtree.
Conclusion
This solution finds the largest BST subtree by checking if the inorder traversal of each subtree is sorted. The algorithm uses recursion to build lists for each subtree and compares their sizes to find the maximum.
