[英]How can i print out my binary tree with a to String method
我對我的二叉樹代碼有疑問。 首先,我有 3 個變量:
數字的int node
boolean lhs = null
左樹
boolean rhs = null
右樹
我想打印出我的二叉樹,但我的代碼不能正常工作:
public String toString () {
if (lhs == null) {
} else if (rhs == null) {
return "Baum ist leer";
}
if (lhs != null) {
}
else if (rhs != null){
return rhs.toString();
}
}
這是我的代碼,但我在控制台中得到的唯一輸出是:
鮑姆·萊爾
...我不知道為什么,因為我的樹不是空的。 我找不到我的錯誤。
這是插入我的樹的代碼:
public void add(int insert) {
if (node > insert) {
if (lhs == null) {
lhs = new Tree(insert);
} else {
lhs.add(insert);
}
} else if (node < insert) {
if (rhs == null) {
rhs = new Tree(insert);
} else {
rhs.add(insert);
}
}
}
您的第一個條件不正確。 這段代碼的意思是:
if (lhs == null) {
//Code here will run if lhs equals to null, regardless the other variables values.
} else if (rhs == null) {
//Code here will run if lhs isn't null, but rhs equals null.
return "Baum ist leer";
}
根據你的回報,我認為如果它們都為空,你可以嘗試讓你的else if
運行,這段代碼就是這樣做的:
if(lhs == null){
if(rhs == null){
//Code here will run only if both lhs and rhs are null.
return "Baum ist leer";
}
}
或者,更干凈的代碼:
if(lhs == null && rhs == null){
//Code here will run only if both lhs and rhs are null.
return "Baum ist leer";
}
如果我誤解了您的目的,請在下面進行實時評論。
您僅將“Baum ist leer”作為返回值的原因是因為您的函數不會返回任何其他內容。 它唯一一次返回文字字符串是在這里:
return "Baum ist leer";
它返回的唯一其他時間是:
return rhs.toString();
..這是一個遞歸調用,只能導致另一個遞歸調用或一些不進行遞歸調用的return
。 而且由於您只有一個不進行遞歸調用的此類return
,因此除了“Baum ist leer”之外,您無法獲得任何其他字符串。
其次,函數應該保證總是返回一個字符串,所以不應該有空的if
塊。
最后,您的toString
方法中沒有讀取節點數據的代碼,因此該函數不可能返回帶有節點數據的字符串。
附注:您將樹節點node
的數據命名為令人困惑。 最常見的是將對象稱為節點,將其數據稱為data
或value
或類似的東西。 但是將其命名為node
令人困惑。
這是一個toString
的實現,它返回一個多行字符串,其中每一行代表一個節點,節點編號的縮進指示它在樹結構中的位置。 根沒有壓痕,因此出現在最左側,而樹最深的葉子將出現在最右側。
// Helper
private String indentedString(Tree tree, String indent) {
if (tree == null) {
return "";
}
return indentedString(tree.rhs, indent + " ")
+ indent + tree.node + "\n"
+ indentedString(tree.lhs, indent + " ");
}
public String toString () {
return indentedString(this, "");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.