在二叉树中返回最大值和最小值

时间:2019-06-05 09:25:36

标签: c++ data-structures binary-tree

我们想编写一个函数,该函数将二叉树的根作为输入,并使用PairAns类返回该树的最大值和最小值。

在这个问题的基本情况下,我遇到了一些问题

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;
}

我希望答案是正确的,但是在所有测试用例中都会遇到运行时错误。

1 个答案:

答案 0 :(得分:0)

考虑一棵有两个节点的树。您可以清楚地看到运行时错误。

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;
    }