问题描述
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);
}