Finding the maximum value in a binary tree I have to find the maximum value in a binary tree. This is how I did it iteratively:

int maxValue(Node* node)
{
    if (node == nullptr)
        throw "BT is empty";

    int max = node-&gt;data;
    for (Node* left = node; left != nullptr; left = left-&gt;left)
    {
        if (left-&gt;data &gt; max)
            max = left-&gt;data;
    }

    for (Node* right = node; right != nullptr; right = right-&gt;right)
    {
        if (right-&gt;data &gt; max)
            max = right-&gt;data;
    }

    return max;
}


I don't know if this is the best way to do it. How can this be improved? Is there a recursive solution?
Trees are often most useful when they're sorted. If the tree is sorted, you can just descend into the right side of the tree.

Since we're assuming an unsorted tree, we have to search the whole thing. Let's build this up by cases. First assume that the current node has the largest value:

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    max = node-&gt;data;
    return max;
}


Nice, but not likely. We can do better. What if the largest value is in the left side of the tree?

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    max = node-&gt;data;

    if(node-&gt;left != nullptr) {
        int leftMax = maxValue(node-&gt;left);
        if(max &lt; leftMax)
            max = leftMax;
    }

    return max;
}


Great! Now we have a function that will check its left side for larger values, all the way down the left side. But what if the largest value is on the right of some node? We'd better cover that case too:

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    int max = node-&gt;data;

    if(node-&gt;left != nullptr) {
        int leftMax = maxValue(node-&gt;left);
        if(max &lt; leftMax)
            max = leftMax;
    }

    if(node-&gt;right != nullptr) {
        int rightMax = maxValue(node-&gt;right);
        if(max &lt; rightMax)
            max = rightMax;
    }

    return max;
}


Now since we only have  to check for NULL that will throw on the first node we can optimize slightly:

int maxValue(Node *node)
{
    if (node == nullptr)
        throw "BT is empty";

    return maxValueNonNull(node, node-&gt;data);
}
int maxValueNonNull(Node* node, int currentMax)
{
    if (node == NULL)
    {    return currentMax;
    }

    currentMax = currentMax &gt; node-&gt;data ? currentMax : node-&gt;data;

    int leftMax  = maxValueNonNull(node-&gt;left,  currentMax);
    int rightMax = maxValueNonNull(node-&gt;right, currentMax);

    return leftMax &gt; rightMax ? leftMax : rightMax;
}


That should do it.