简体   繁体   中英

return max and min in a binary tree

We want to write a function that takes the root of a binary tree as input and returns max and min of that tree using a class PairAns.

I have some problem in the base case of this problem

PairAns minMax(BinaryTreeNode<int> *root) {
    PairAns ans;
    ans.max=INT_MIN;
    ans.min=INT_MAX;
    if(root->left==NULL&&root->right==NULL){
        ans.max=root->data;
        ans.min=root->data;
        return ans;
    } 
    PairAns smallans1=minMax(root->left);
    PairAns smallans2=minMax(root->right);
    ans.max=max(max(smallans1.max,smallans2.max),root->data);
    ans.min=min(min(smallans1.min,smallans2.min),root->data);
    return ans;
}

I expect the answer to be correct but am getting a run-time error in all the test cases.

Consider a tree with two nodes. You can clearly see a runtime error.

PairAns minMax(BinaryTreeNode<int> *root) {

    PairAns ans;`enter code here`
    ans.max=INT_MIN;
    ans.min=INT_MAX;

    if(root == NULL)
       return ans;

    if(root->left==NULL&&root->right==NULL){
    ans.max=root->data;
    ans.min=root->data;
    return ans;
    } 
    PairAns smallans1=minMax(root->left);
    PairAns smallans2=minMax(root->right);
    ans.max=max(max(smallans1.max,smallans2.max),root->data);
    ans.min=min(min(smallans1.min,smallans2.min),root->data);
    return ans;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM