修剪二叉搜索树
我应该编写一个方法,将两个整数作为最小值和最大值。然后,它从树中删除所有小于最小值且大于最大值的整数。到目前为止我的代码非常丑陋并且根本不起作用。我什至不确定我是否走在正确的道路上......
private SearchTree<Integer> trim(SearchTreeNode<Integer> e, int min, int max){
if (e != null){
if (e.left.data.compareTo(min) <= 0){
remove((E) e.left);
} else {
}
}
}
I am supposed to write a method that takes in two integers as a min and max. Then it removes any integers from the tree that are less than the minimum and larger than the maximum. The code I have so far is very ugly and does not work at all. I'm not even sure if it I am on the correct path or not...
private SearchTree<Integer> trim(SearchTreeNode<Integer> e, int min, int max){
if (e != null){
if (e.left.data.compareTo(min) <= 0){
remove((E) e.left);
} else {
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关于没有任何代码的算法的一些一般想法:
您需要首先实现
delete
。二叉搜索树中的delete
具有特定且定义良好的行为;你需要首先实现这一点(你的教授应该已经讨论过它)。我想说你80%的工作都是在这里完成的。剩下的20%用于实现
find
功能。您现在可以组合这两个函数并实现trim
函数。如果您解释一下到目前为止您所做的事情,我们也许可以给您一些提示并引导您走向正确的方向。这里最重要的是学习!
UPDATE
是的,需要遍历树并删除符合条件的节点。就递归而言,想想通常如何遍历二叉搜索树。
现在您需要添加
contains
和remove
。这部分是微不足道的,但棘手的部分是,当你遍历树时,树正在发生变化。但如果你想一想,应该没那么难。提示:当您删除 BST 中的节点时,您实际上并没有删除它,除非它是叶节点。您只需替换它的值即可。所以遍历应该不会受到影响。Some general ideas about the algorithm without any code:
You need to implement
delete
first.delete
in a Binary Search Tree has specific and well-defined behavior; you need to implement this first (your professor should have gone over it). I'd say that 80% of your work is done here.The remaining 20% is for implementing the
find
function. You can now combine both functions and implement yourtrim
function.If you explain what you have done so far, we might be able to give you some hints and move you in the correct direction. The important thing here is to learn!
UPDATE
Yes, you need to traverse the tree and delete nodes that meet the criteria. As far as recursion is concerned, think about how you would traverse the binary search tree normally.
Now you need to add in the
contains
and theremove
. That part is trivial, but the tricky part is that the tree is changing as you are traversing it. But if you think about it, it shouldn't be that hard. Hint: When you delete a node in a BST, you don't actually remove it unless it's a leaf node. You merely replace its value. So traversal shouldn't be affected.您的问题的伪代码是。
Pseudo code for your problem is.
也许你可以实现迭代器接口,遍历构成 BST 的元素,将满足约束的元素放入新的 BST 中
然后你让原来的 BST 等于新的 BST。
问候。
Maybe you could implement the iterator interface, go through the elements that constitute your BST, whichever element meets your constraint is put in a new BST
then you make your original BST equal to the new one.
Regards.