I'm learning the BST recursive construction and found that the insert
method does not use return
keyword when implementing recursion, but the contains
method do use the return
key word. Can anybody explain this to me? Many thanks!
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并不是作为一个函数实现而是包含is,这意味着insert只是具有副作用,因此它将更改BST的状态。
The fact it returns
this
at the end is not necessary, it could just as easily have a void return value. A functional version would return a new BST that is like the original but with the element inserted, and that would require use of the returned value, there would be a bit more complexity there.“插入”函数最后仅具有一个return语句,因为它仅需返回“ this”,而不依赖于外部因素和函数的执行。
因此,简短的版本:在需要时使用“ return”,而在不需要时不使用“ return”。