我编写此代码来搜索键,然后打印大于此键的所有节点
public boolean search(int data) {
return search(root, data);
}
private boolean search(BSTnode p, int data) {
if (p == null)
return false;
else {
// if the data we are searching for is found at p (at the current root)
if (data == p.getData())
return true;
else if (data < p.getData())
return search(p.getLeft(), data);
else
return search(p.getRight(), data);
}
}
我尝试使此代码打印所有大于键的节点
public void printAllNodeGreaterMyFoundNode(int data) {
printAllNodeGreaterMyFoundNode(root, data);
}
private void printAllNodeGreaterMyFoundNode(BSTnode p, int data){
if(data<p.getData())
System.out.print(p.getData());
最后这是我的空主
System.out.print("> What value do you want to search for: ");
value = input.nextInt();
if (myTree.search(value)){
System.out.println("> " + value + " was found in the tree and the values greater than "+value+"are:");
myTree.printAllNodeGreaterMyFoundNode(value);
有人可以帮我吗?
最佳答案
方法1:当每个BSTNode都可以访问其父节点时
public void printGreater(BSTNode root, int value) {
BSTNode data = search(root, value);
BSTNode succ;
if (data != null) {
System.out.println("> " + value + " was found in the tree and the values greater than " + value + "are:");
while (data != null) {
succ = successor(data);
if (succ != null) {
System.out.println(succ.data);
}
data = succ;
}
}
}
private BSTNode search(BSTNode p, int data) {
if (p == null)
return null;
else {
// if the data we are searching for is found at p (at the current
// root)
if (data == p.data)
return p;
else if (data < p.data)
return search(p.left, data);
else
return search(p.right, data);
}
}
在主方法中
System.out.print("> What value do you want to search for: ");
value = input.nextInt();
printGreater(bstRootNode, value);
方法二:如果无法访问BSTNode类中的父节点
public void printGreaterWithoutParent(BSTNode root, int value) {
BSTNode data = search(root, value);
if (data != null) {
System.out
.println("> " + value + " was found in the tree and the values greater than " + value + "are:");
greaterNodes(root, data);
}
}
private void greaterNodes(BSTNode n, BSTNode k) {
if (n == null)
return;
greaterNodes(n.left, k);
if (n.data > k.data) {
System.out.println(n.data);
}
greaterNodes(n.right, k);
}
在主方法中
System.out.print("> What value do you want to search for: ");
value = input.nextInt();
printGreaterWithoutParent(bstRootNode, value);
关于java - 如何打印树中大于特定节点的所有节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250522/