KatInterview

Recursive Maximum Search in an Arbitrary Binary Tree

Trees & GraphsModel answer
MediumModel answerTrees & Graphsrecursionbinary-treetraversal

Last 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), return INT_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_MIN serves 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.