我正在编写代码来解决"恢复二进制搜索树"问题。
https://oj.leetcode.com/problems/recover-binary-search-tree/
首先我编写了这段代码,将 recoverTree 函数中的三个指针放出来:
class Solution {
public:
TreeNode *pre;
TreeNode *first;
TreeNode *second;
void recoverTree(TreeNode *root) {
inOrder(root);
int temp = first->val;
first->val = second->val;
second->val = temp;
return;
}
void inOrder(TreeNode *root) {
if (!root) return;
inOrder(root->left);
if (!pre) {
pre = root;
} else {
if (pre->val > root->val) {
if (!first) first = pre;
second = root;
}
pre = root;
}
inOrder(root->right);
}
};
它工作正常,经过所有测试。然后我想也许不会把三个指针的定义放在函数之外。所以我写了这样的话:
class Solution {
public:
void recoverTree(TreeNode *root) {
TreeNode *pre;
TreeNode *first;
TreeNode *second;
inOrder(root, pre, first, second);
int temp = first->val;
first->val = second->val;
second->val = temp;
return;
}
void inOrder(TreeNode *root, TreeNode *&pre, TreeNode *&first, TreeNode *&second) {
if (!root) return;
inOrder(root->left, pre, first, second);
if (!pre) {
pre = root;
} else {
if (pre->val > root->val) {
if (!first) first = pre;
second = root;
}
pre = root;
}
inOrder(root->right, pre, first, second);
}
};
但这不起作用。我使用引用或其他任何导致错误的内容有什么问题吗?