繁体   English   中英

在二叉搜索树中找到具有最小值的节点(打印该节点)

[英]find the node with minimum value in a binary search tree (print that node)

我必须在二叉搜索树中找到具有最小值的节点。我写了 function 但我无法显示具有最小值的节点。这是树

struct Node
{
    int key; 
    void *info; 
    Node *left, *right;
};

这是 function

Node* findMin(Node* r)
{
    if (r == 0)
        return 0;
    else if (r->left == 0)
        return r;
    else
        return findMin(r->left);
}

我在主文件中这样调用 function:

Node *root = makeTree(); // I enter the values and insert them into a binary search tree with an insert function.
root = findMin(root);
cout << root;

它显示地址而不是值。我应该如何显示具有最小值的节点?

在这份声明中

root = findMin(root);

您正在覆盖指向树根节点的指针。

function可以看如下方式

Node * findMin( Node *node )
{
    return node == nullptr || node->left == nullptr ? node : findMin( node->left );
}

显示找到的值写入

auto node = findMin( root );

if ( node ) std::cout << node->key << '\n';
int minValue(struct node* node)  
{  
    struct node* current = node;  

    /* loop down to find the leftmost leaf */
    while (current->left != NULL)  
    {  
        current = current->left;  
    }  
    return(current->data);  
}

它显示地址而不是值。我应该如何显示具有最小值的节点?

这是因为您需要取消引用指针以显示值。 在您的主要 function 内部:

Node *root = makeTree();
root = findMin(root);
if (root)
    cout << root->key;
else
    cout << "Tree empty\n";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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