Algorithm Steps
- Given a binary search tree, if the tree is empty, return
null
or an appropriate value. - Initialize a variable
current
with theroot
node. - While
current.right
is notnull
, setcurrent
tocurrent.right
. - Once
current.right
isnull
, thecurrent
node holds the maximum value in the BST. - Return
current.val
as the maximum value.
Find the Maximum Value in a Binary Search Tree - Code Examples Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
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))