我可以喊但不返回原因?请提出修改建议

问题描述

enter image description here我可以退出A->val,但不能返回A->val。为什么?因为我们在for循环内只能走一次,它应该返回它。请解释这样返回的逻辑错误。还建议任何更改。感谢您的帮助。

/**

* Definition for a binary tree node.

* struct TreeNode {

*     int val;

*     TreeNode *left;

*     TreeNode *right;

*     TreeNode() : val(0),left(nullptr),right(nullptr) {}

*     TreeNode(int x) : val(x),right(nullptr) {}

*     TreeNode(int x,TreeNode *left,TreeNode *right) : val(x),left(left),right(right) {}

* };

*/

class Solution {
 public:
  int kthSmallest(TreeNode* A,int B) {
    if (A == NULL)

    {
      return -1;
    }

    int res;

    int k = B;

    static int i = 0;

    if (A != NULL)

    {
      kthSmallest(A->left,B);

      i++;

      if (i == k)

      {
        int res = A->val;

        cout << A->val;

        return res;
      }

      kthSmallest(A->right,B);
    }

    return -111;
  }
};

解决方法

这样的事情如何实现,将功能覆盖以将num初始化为0

const TreeNode *kthSmallest(const TreeNode *A,const int k,int &num) {
    if (!A) return nullptr;

    const TreeNode *left = kthSmallest(A->left,k,num);
    if (left != nullptr) return left;

    num++;
    if (k == num) return A;

    return kthSmallest(A->right,num);
}

const TreeNode *kthSmallest(const TreeNode *A,const int k) {
    int num{};
    return kthSmallest(A,num);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...