![](/img/trans.png)
[英]Better way to return from recursive function when there are 2^n conditions
[英]When to use return in recursive function?
我正在學習BST遞歸構造,發現insert
方法在實現遞歸時沒有使用return
關鍵字,但是contains
方法確實使用了return
關鍵字。 有人可以向我解釋一下嗎? 非常感謝!
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
public BST insert(int value) {
// Write your code here.
// Do not edit the return statement of this method.
if (value < this.value) {
if (left == null) {
BST newBST = new BST(value);
left = newBST;
} else {
left.insert(value);
}
} else {
if (right == null) {
BST newBST = new BST(value);
right = newBST;
} else {
right.insert(value);
}
}
return this;
}
public boolean contains(int value) {
// Write your code here.
if (value < this.value) {
if (left == null) {
return false;
} else {
return left.contains(value);
}
} else if (value > this.value) {
if (right == null) {
return false;
} else {
return right.contains(value);
}
} else{
return true;
}
}
本質上是因為 insert 沒有實現為 function 但包含 is,這意味着 insert 只是有副作用,它改變了 BST 的 state。 包含本質上是 function - 它返回給定輸入的答案。
事實上 insert 在最后返回this
是不必要的,它可以很容易地有一個 void 返回值。
功能版本將返回一個新的 BST,它與原始版本類似,但插入了元素,並且需要使用返回的值,那里會有更多的復雜性。 (我不是在這里提倡功能版本!)
“插入” function 最后只有一個 return 語句,因為它所要返回的只是“this”,而不是依賴於外部因素和 function 的執行。
所以,簡短的版本:你需要時使用“return”,不需要時不要使用“return”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.