繁体   English   中英

从 c 中的二叉树中获取最小的三个数字

[英]Get smallest three numbers from binary tree in c

我使用 inorder function 从最小到最大元素在二叉搜索树中打印数据。 我怎么能只打印前三个最小的元素?

void inorder(struct node *root)
{
    // Depth-first
    // Inorder (LDR) --> <left> <data> <right>

    if(root == NULL)
        return;

    indorder(root -> left_child);

    printf("%d ", root -> value);

    inorder(root -> right_child);
}

我想为第一个 n 元素添加新参数

void inorder(struct node *root, int n)

让你的 function 返回n的新值,这样在递归调用之后你可以看到n是否仍然是正数并且应该打印当前节点的值。 如果没有,那么您可以退出递归树,因为没有什么可做的了:

int inorder(node *root, int n) {
    if (root == NULL || n <= 0) // Nothing to print here.
        return n;
    n = inorder(root -> left_child, n);
    if (n <= 0) // All required prints have been done, so exit recursion tree
        return 0;
    printf("%d ", root -> value);
    // Previous print counts as 1, so pass one less to next call:
    return inorder(root -> right_child, n-1);
}

暂无
暂无

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

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