Find the Maximum Value in a Binary Search Tree

Visualization

Algorithm Steps

  1. Given a binary search tree, if the tree is empty, return null or an appropriate value.
  2. Initialize a variable current with the root node.
  3. While current.right is not null, set current to current.right.
  4. Once current.right is null, the current node holds the maximum value in the BST.
  5. 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))