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->data;
for (Node* left = node; left != nullptr; left = left->left)
{
if (left->data > max)
max = left->data;
}
for (Node* right = node; right != nullptr; right = right->right)
{
if (right->data > max)
max = right->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?