Skip to main content
edited title
Link
lightning_missile
  • 2.8k
  • 2
  • 24
  • 42

FInding Finding the maximum value in a binary tree

deleted 2 characters in body; edited title
Source Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Better way to find FInding the maximum value in a Binary Treebinary tree

Better way to find FInding the maximum value in a Binary Treebinary 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->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?

Better way to find 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->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?

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->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?

edited tags
Link
200_success
  • 145.6k
  • 22
  • 190
  • 479
re-did previous edit (collision)
Source Link
Edward
  • 67.2k
  • 4
  • 120
  • 284
Loading
[Edit removed during grace period]
Source Link
user6607
  • 377
  • 2
  • 3
  • 8
Loading
Source Link
user6607
  • 377
  • 2
  • 3
  • 8
Loading