Problem Statement
You are given the root of a Binary Search Tree (BST). Your task is to find and return the maximum value present in the tree. If the tree is empty, return null
or any equivalent value indicating the tree has no nodes.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findMax(root):
if not root:
return None
current = root
while current.right:
current = current.right
return current.val
# Example usage:
if __name__ == '__main__':
# Construct BST:
# 10
# / \
# 5 15
# \
# 20
root = TreeNode(10, TreeNode(5), TreeNode(15, None, TreeNode(20)))
print('Max value:', findMax(root))