我想知道爲什麼我在此代碼中獲得與方法containsData
和containsData2
相同的結果。樹搜索功能沒有給出預期的結果
package rr.fe.op.lab.proc;
class TreeNode {
TreeNode left;
TreeNode right;
String data;
}
class TreeProgram {
public static void main(String[] args) {
TreeNode node = null;
node = insert(node, "Han");
node = insert(node, "Luke");
node = insert(node, "Leia");
node = insert(node, "Padme");
node = insert(node, "Vader");
node = insert(node, "Yoda");
System.out.println("Writing tree inorder:");
writeTree(node);
node = reverseTreeOrder(node);
System.out.println("Writing reversed tree inorder:");
writeTree(node);
int size = sizeOfTree(node);
System.out.println("Number of nodes in tree is "+size+".");
boolean found = containsData(node, "Padme");
System.out.println("Searched element is found: "+found);
boolean found1 = containsData2(node, "Padme");
System.out.println("Searched element is found: "+found);
}
static boolean containsData(TreeNode treeRoot, String data) {
if(treeRoot == null)
return false;
else if(data.compareTo(treeRoot.data) == 0)
return true;
else if(data.compareTo(treeRoot.data) < 1)
return containsData(treeRoot.left,data);
else
return containsData(treeRoot.right,data);
}
static int sizeOfTree(TreeNode treeRoot) {
if(treeRoot == null)
return 0;
else
return 1 + sizeOfTree(treeRoot.right) + sizeOfTree(treeRoot.left);
}
static TreeNode insert(TreeNode treeRoot, String data) {
if(treeRoot == null){
TreeNode newnode = new TreeNode();
newnode.data = data;
newnode.left = null;
newnode.right = null;
return newnode;
}
else if (data.compareTo(treeRoot.data) < 1)
treeRoot.left = insert(treeRoot.left,data);
else
treeRoot.right = insert(treeRoot.right,data);
return treeRoot;
}
static void writeTree(TreeNode treeRoot) {
if(treeRoot != null){
writeTree(treeRoot.left);
System.out.println(treeRoot.data);
writeTree(treeRoot.right);
}
}
static TreeNode reverseTreeOrder(TreeNode treeRoot) {
if(treeRoot == null)
return null;
TreeNode node = new TreeNode();
node = treeRoot.left;
treeRoot.left = treeRoot.right;
treeRoot.right = node;
reverseTreeOrder(treeRoot.left);
reverseTreeOrder(treeRoot.right);
return treeRoot;
}
static boolean containsData2(TreeNode treeRoot,String data){
if (treeRoot == null) {
return false;
}
if (treeRoot.data == data){
return true;
} else {
return containsData2(treeRoot.left,data) || containsData2(treeRoot.right,data);
}
}
}
我知道在倒轉樹之前,方法containsData
工作正常。當我倒轉樹時,它不工作,這是可以的。我寫了一個方法containsData2
,想法該方法可以找到樹是否顛倒的元素。當然,複雜性會更高。但是,與containsData2
,我得到了相同的結果containsData
,即false
。我做錯了什麼?
你試過調試它嗎?也許你的'treeRoot'是空的。 – SomeJavaGuy