我是 Java 和編程的新手。代碼作業,主要是。除了當我輸入以下內容時,它可以做任何事情:
順序:
d, e, f, a, b, c, g, h, i, j.搜索:
b或c
我似乎找不到代碼的任何問題,但已將其范圍縮小到insertNode模塊/類,似乎當用戶僅在左側注冊節點a, b, c后鍵入時。d, e, f,a
import java.util.Arrays;
import java.util.Scanner;
import java.lang.reflect.Method;
public class BinarySearchTreeTestStackOverflow {
class Node {
String stringData;
Node leftChild;
Node rightChild;
Node(String stringData) {
this.stringData = stringData;
leftChild = rightChild = null;
}
}
//root node for the binary tree
Node root;
//Constructor method
public BinarySearchTreeTestStackOverflow() {
root = null;
}
//Insert method for new values in the tree
public void insert(String key) {
root = insertNode(root, key);
}
//Insert recursive call for inserting from the root, in the right place
public Node insertNode(Node node, String key) {
if (node == null) {
node = new Node(key);
return node;
}
if (key.compareTo(node.stringData) < 0) {
node.leftChild = insertNode(node.leftChild, key);
} else if (key.compareTo(root.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
return node;
}
//Find method asking for the node to find
public Node find(String key) { //takes user input and turns it into a node
Node node = findNode(root, key);
System.out.println("print key to find: " key);
return node;
}
//Find recursive method using the root node.
public Node findNode(Node node, String key) {
if (key.compareTo(node.stringData) == 0) {
return node;
}
//check up on findNodeMethod
if (key.compareTo(node.stringData) <= 0) {
if (node.leftChild == null) {
return null;
} else {
return findNode(node.leftChild, key);
}
} else if (key.compareTo(node.stringData) > 0) {
if (node.rightChild == null) {
return null;
} else {
System.out.println("went right"); //toDelete
return findNode(node.rightChild, key);
}
}
return null;
}
public static void main(String[] args) {
BinarySearchTreeTestStackOverflow binaryTree = new BinarySearchTreeTestStackOverflow();
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 10; i ) {
System.out.print("Enter string " i " for the tree: ");
binaryTree.insert(scanner.nextLine());
}
System.out.print("Enter the value to be searched: ");
String key = scanner.nextLine(); //correct, verified using - System.out.println("key to be searched: " key);
Node node = binaryTree.find(key);
if (node == null) {
System.out.println("The string does not exist");
} else {
System.out.println("Node " node.stringData " was found");
}
}
}
uj5u.com熱心網友回復:
問題在里面insertNode()。而不是與比較root:
else if (key.compareTo(root.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
你應該與node:
else if (key.compareTo(node.stringData) > 0) {
node.rightChild = insertNode(node.rightChild, key);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/379979.html
上一篇:Python,用鍵排序
下一篇:字串順序(從左到右和從右到左)
