[英]BST - counting nodes with left and right children
如標題中所述,我試圖通過僅計算BST中同時具有左右子節點的節點來解決此問題。 我正在努力思考解決這個問題的邏輯。
我想到了這樣的事情。
首先,檢查根是否為空或子級是否為空。 接下來,遍歷右轉的樹並繼續檢查子級,在滿足條件時增加一個計數器。 但是,當我到達末端節點並需要返回到有一個左孩子要遍歷的節點時會發生什么? 我有一個臨時節點來跟蹤最近的父級,但是當我需要上一層以上時該怎么辦? 我以為這個問題的答案是遞歸地解決它,但我什至不知道從哪里開始。
這是我所擁有的:
public int fullNodes() {
int count = 0;
Node n = root;
Node temp = null;
if (n == null || n.left == null && n.right == null) return count;
count++; //increment count, since the root has children on both sides
temp = n; //hold the previous place
n = n.right; //go right
//Now what?
return count;
}
解決問題時,我仍在努力進行遞歸思考,除了我的問題之外,您如何學習遞歸思考? 只是大量的實踐,還是您使用一些技巧來解決問題?
在子節點上調用相同的函數,而不是使用temp變量來保存前一個節點(只能在深度為1的情況下使用)。
遞歸樹遍歷可能看起來像這樣:
public int countSomething (Node node) {
// Self;
//
int result = 1; // use your required logic here
// Children;
//
if (node.left != null)
result += countSomething( node.left);
if (node.right != null)
result += countSomething( node.right);
// done.
return result;
}
// example usages
int treeTotal = countSomething( rootNode);
int subtreeTotal = countSomething( subtree);
然后,執行調用堆棧將保留函數的遞歸調用,每個調用都具有其適當的上下文。 當頂級調用返回時,它將匯總被調用的整個樹或子樹的答案。
為您的BST“節點同時具有左右兩個子節點”輸入適當的邏輯,而不是常量1。
首先讓我們創建您的Node類的表示形式
class Node {
public Node left;
public Node right;
public Node(){}
public Node(Node left, Node right) {
this.left = left;
this.right = right;
}
}
然后,我們編寫我們的可恢復函數和使用您函數的客戶端
public class Main {
public static int countNodes(Node root) {
if(root!=null && root.left!=null && root.right!=null) {
return 1+countNodes(root.left)+countNodes(root.right);
}
return 0;
}
public static void main(String[] args) {
Node right = new Node();
Node left = new Node();
Node root = new Node(left, right);
root.right = new Node(new Node(), new Node());
System.out.println(countNodes(root));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.