[英]Java Binary Search Tree _ the distance from root to nearest leaf
我想知道在Binary Search樹中計算距根最近的葉子距離的基本算法
我想使用這樣的代碼,
public int closeness() {
return closeness(root);
}
public int closeness(Node x) {
}
謝謝。
您需要取每個分支的最小“親密度”加一個:
public int closeness(Node x) {
if (x == null) {
return Integer.MAX_VALUE;
}
if (x.left == null && x.right == null) {
return 0;
}
return Math.min(closeness(x.left), closeness(x.right)) + 1;
}
或者,如果沒有“ MAX_VALUE”把戲,則在忽略Math.min()中的空分支時會更加冗長
public int closeness(Node x) {
if (x.left == null) {
if (x.right == null) {
return 0;
}
return closedness(x.right) + 1;
}
if (x.right == null) {
return closedness(x.left) + 1;
}
return Math.min(closeness(x.left), closeness(x.right)) + 1;
}
實現您的需求的一個快速想法是遞歸地遍歷BST(左右子樹),並一路計算到達葉節點之前必須經過的節點數。 最后,您可以使用簡單的MIN / MAX函數來確定距根最近的葉子節點。 請注意,該想法適用於計算距離,而不是實際(最近的)葉節點本身。 我認為,實現這一目標應該不會太困難。 如有任何其他問題,請隨時提問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.