Recursive Maximum Search in an Arbitrary Binary Tree
Trees & GraphsModel answerLast updated
Write a recursive function that traverses a binary tree to locate the largest integer value, accounting for null pointers and negative-only trees.
You are given the root of a binary tree where each node contains an integer. Your task is to write a recursive function that returns the largest value present anywhere in the tree.
Use this node structure:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
Function Signature
int findMax(TreeNode* root);
Requirements
- When the input tree is empty (root is
nullptr), returnINT_MIN(the smallest representable 32-bit signed integer). - The tree may contain any combination of positive, negative, or zero values.
- Nodes are not arranged in any sorted order—this is an arbitrary binary tree, not a binary search tree.
- Be mindful that
INT_MINserves both as the sentinel for "no tree" and as a potentially valid node value.
Constraints
- Number of nodes: 0 to 10⁵
- Node values: -2³¹ ≤
val≤ 2³¹ - 1 - Tree height: may reach N in the worst case (completely unbalanced)
Examples
Example 1
1
/ \
3 2
/ / \
5 4 7
Input: root of the tree above
Output: 7
Explanation: The tree contains {1, 3, 2, 5, 4, 7}; the maximum is 7.
Example 2
-10
/ \
-20 -3
Input: root of the tree above
Output: -3
Explanation: All nodes hold negative integers. The largest is -3.
Example 3
Input: nullptr
Output: -2147483648 (INT_MIN)
Explanation: An empty tree returns the sentinel value.
Hints
Hint 1
Since the tree is not sorted, every node must be examined—no shortcuts.
Hint 2
The smallest possible integer acts as a neutral element when taking maximums, so it naturally handles missing subtrees.
Hint 3
Consider what happens if every node actually holds INT_MIN—your function still returns the correct numeric answer, though it cannot distinguish that case from an empty tree.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because the tree has no ordering constraint, the maximum value could reside at any node. We must visit every node. The natural recursive decomposition is:
max_value(node) = max(node.val, max_value(left_child), max_value(right_child))
Base case: When a pointer is nullptr, return INT_MIN. This value is the identity element for the max operation over 32-bit integers: for any valid x, max(x, INT_MIN) = x. Consequently, a missing child never influences the result, and an entirely empty tree correctly returns INT_MIN as required.
This is a post-order traversal pattern: evaluate both subtrees, then combine their results with the current node's value.
Correctness
We can verify correctness by induction on tree structure:
- Base: An empty tree (null pointer) returns
INT_MIN, matching the specification. - Inductive step: Assume the function correctly computes the maximum for the left and right subtrees. Every node in the full subtree is either the current node itself, a node in the left subtree, or a node in the right subtree. The maximum over the entire subtree is therefore the maximum of these three components. A null child contributes
INT_MIN, which never exceeds any real value.
Edge case—all nodes hold INT_MIN: The function returns INT_MIN, which is numerically correct. However, the return value is indistinguishable from an empty tree. This is a limitation of using an in-band sentinel rather than an out-of-band signal (like std::optional), but it does not violate the stated contract.
Complexity
- Time: O(N), where N is the number of nodes. Every node is visited exactly once, and each visit performs constant-time work (two recursive calls and a comparison).
- Space: O(H) for the call stack, where H is the tree height.
- Balanced tree: O(log N)
- Skewed tree: O(N), meaning up to 10⁵ stack frames in the worst case. This is typically safe in C++ with default stack limits, but in Python it exceeds the default recursion limit and may require adjustment or an iterative approach.
Common Mistakes
- Initializing the running maximum to 0: This fails when all values are negative, because 0 would incorrectly become the result.
- Assuming the tree is a BST: Treating it as sorted and only checking the rightmost path would miss the true maximum.
- Forgetting to check both children: Stopping after one subtree returns a value can miss the actual maximum in the other branch.
- Ignoring the deep-skew case: Not recognizing that O(N) stack depth can be a practical concern for very unbalanced trees.
Solution (Python)
from typing import Optional
INT_MIN = -(2 ** 31)
class TreeNode:
def __init__(self, val: int, left: Optional["TreeNode"] = None,
right: Optional["TreeNode"] = None):
self.val = val
self.left = left
self.right = right
def find_max(root: Optional[TreeNode]) -> int:
"""Return the maximum value in the tree, or INT_MIN if empty."""
if root is None:
return INT_MIN
left_max = find_max(root.left)
right_max = find_max(root.right)
return max(root.val, left_max, right_max)
Solution (C++)
#include <algorithm>
#include <climits>
int findMax(TreeNode* root) {
if (!root) return INT_MIN;
return std::max({root->val, findMax(root->left), findMax(root->right)});
}
What Strong Candidates Demonstrate
- Recognizing immediately that full traversal is necessary because the tree is unordered.
- Choosing
INT_MINas the base return value and articulating why it serves as the identity formax. - Acknowledging the O(H) space cost and the worst-case scenario of a skewed tree without prompting.
- Identifying the ambiguity when a non-empty tree's maximum coincides with the sentinel, and suggesting cleaner alternatives like returning an
optionalor throwing an exception for empty input.
Follow-Up Directions
- Eliminate the sentinel ambiguity: Return
std::optional<int>in C++ (orNonein Python for empty trees), making the "no value" state explicit in the type system. - Iterative version: Implement the same logic using an explicit stack or queue to avoid deep recursion and handle trees with extreme heights safely.
- BST optimization: If the tree were guaranteed to be a binary search tree, the maximum would always be the rightmost node, reducing the solution to a simple pointer-following loop with O(H) time and O(1) space.