发现小于X的所有号码在BST

编程入门 行业动态 更新时间:2024-10-25 08:14:42
本文介绍了发现小于X的所有号码在BST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将如何做到这一点?我不知道当我将停止BST搜索。

how would i do this? I am not sure when I would stop the bst search.

推荐答案

如果你的树的每个节点都有 numLeft 字段,告诉你有多少个节点有在其左子树(计算本身也是如此),那么您可以在 O(日志N)

If each node of your tree has a field numLeft that tells you how many nodes there are in its left subtree (counting itself too), then you can do this in O(log N)

只要保持添加 numLeft 来一个全局结果变量对每个节点的值小于 X :

Just keep adding numLeft to a global result variable for each node whose value is less than x:

countLessThan(int x, node T) if T = null return if T.value >= x countLessThan(x, T.left) // T.left contains only numbers < T.value and T.right only numbers > T.value else globalResult += T.numLeft countLessThan(x, T.right)

这将只计算的数字。如果你想打印出来,你需要编写,将打印给定的参数子树的深度优先遍历。你可以找到很多这样的网上,所以我不会发表。

This will only count the numbers. If you want to print them, you need to write a depth first traversal that will print a subtree given as parameter. You can find plenty of those online, so I won't post that.

更多推荐

发现小于X的所有号码在BST

本文发布于:2023-11-29 23:04:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:号码   发现   BST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!