何时在递归函数中使用return?

问题描述 投票:-1回答:2

[我正在学习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;
            }
    }
java algorithm recursion binary-search-tree
2个回答
0
投票

“ insert”函数最后只具有一个return语句,因为它只需要返回“ this”,而不依赖于外部因素和函数的执行。

因此,简短版本:您在需要时使用“返回”,而在不需要时不使用“返回”。


0
投票

本质上是因为insert并不是作为一个函数实现,而是包含is,这意味着insert只是有副作用,它会更改BST的状态。 Contains本质上是一个函数-它返回给定输入的答案。

事实插入结尾不需要返回this,它可以很容易地获得空返回值。

功能版本将返回一个新的BST,该BST与原始BST相似,但是插入了元素,并且这将需要使用返回的值,因此那里会有更多的复杂性。(我这里不提倡功能版本!)

© www.soinside.com 2019 - 2024. All rights reserved.