[英]Find the smallest element greater than data, or the successor (Binary Search Tree)
我有一个BST类和BSTNode类,它们都具有可比性,我需要从二进制搜索树中找到大于数据或后继元素的最小元素。 我知道我有两种情况
1:右子树为非空,则后继者为右子树的最左节点
2:右子树为空,则后继子是包含数据的节点的最低祖先,其左子节点也是给定数据的祖先。 例:
73
/ \
34 90
/ \
32 40
如果我们需要找到下一个最大的40,则将返回73。
public T nextLargest(T data) {
return helperNL(data, root);
}
private T helperNL(T data, BSTNode<T> root) {
if (data == null) {
throw new IllegalArgumentException("You can't look for null data");
}
if (root == null) {
return null;
}
if (root.getRight() != null) {
BSTNode<T> dummyNode = root.getRight();
//getting the leftmost node
while (dummyNode.getLeft() != null) {
dummyNode = dummyNode.getLeft();
}
return dummyNode.getData();
}
return null;
}
这是我到目前为止的代码。 任何帮助,将不胜感激!
只需进行基本的顺序遍历即可。 采取任何静态变量来存储刚刚遍历的节点的数据。 如果它等于数据(必须找到其后继数据),则打印当前节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.