[英]counting the right nodes of a binary tree
我想計算一棵二叉樹的正確節點,例如以下一個:
15
/
10
\
14
所以我做了以下程序:
public class NodeT {
int elem;
NodeT left;
NodeT right;
public NodeT(int elem){
this.elem=elem;
left=null;
right=null;
}
}
public class Tree {
public NodeT createTree(){
NodeT root=new NodeT(15);
NodeT n1=new NodeT(10);
NodeT n4=new NodeT(14);
root.left=n1;
n1.right=n4;
return root;
}
public int countRight(NodeT root){
if (root==null) return 0; //version 1
else{
return 1+countRight(root.right);
}
}
我通過以下方式調用了我的主程序:
Tree tree=new Tree();
NodeT root=tree.createTree();
System.out.println(tree.countRight(root))
此代碼打印 1 作為正確答案,但我不明白為什么會發生這種情況。 對於我看到的 15 的右分支等於 null,因此對遞歸函數 countRight() 的調用應返回 0 並打印不正確的答案。
我看過其他解決方案,我發現為了計算所有節點,他們使用如下解決方案:
static int n;
public int countRight(NodeT root){ //version 2
if (root==null) return 0;
if (root.left!=null){
n=countRight(root.left);
}
if (root.right!=null){
n++;
n=countRight(root.right);
}
return n;
}
這對我來說似乎更合法。 會不會是第一個版本失敗的情況?
謝謝
這樣的方法永遠不要使用靜態字段或與此相關的任何字段。
任務是計算正確的節點數,這實際上意味着計算right
不為空的節點數。 您並不是真正在計算節點,而是在對節點的引用。
這也意味着您必須掃描所有節點,這意味着該方法必須同時左右移動。
最后,根節點根據定義不是正確的節點。
public int countRight(NodeT node) {
if (node == null)
return 0;
if (node.right == null)
return countRight(node.left);
return 1 + countRight(node.left) + countRight(node.right);
}
您的第一個代碼將重新運行2,它不會以遞歸方式返回1
返回1 +另一個更深層次的調用,直到root.right == null
將根據您的結構產生2個返回值,您所編碼的樹與您繪制的樹不同
假設您無法調試,則僅在參數“ NodeT root”為null時返回0。
我想你要:
public int countRight(NodeT root, int currentDepth){
if (root==null
|| root.right == null) // missing this comparison
return currentDepth;
else{
return countRight(root.right, currentDepth++);
}
}
Tree tree=new Tree();
NodeT root=tree.createTree();
System.out.println(tree.countRight(root), 0) // 0 is the begin
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.