leetcode-----99. 恢复二叉搜索树
Posted 景云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-----99. 恢复二叉搜索树相关的知识,希望对你有一定的参考价值。
代码
/**
* 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), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
TreeNode *first = NULL, *second, *last= NULL;
while (root) {
if (!root->left) {
if (last && last->val > root->val) {
if (!first) first = last, second = root;
else second = root;
}
last = root;
root = root->right;
} else {
auto p = root->left;
while (p->right && p->right != root) p = p->right;
if (!p->right) p->right = root, root = root->left;
else {
p->right = NULL;
if (last && last->val > root->val) {
if (!first) first = last, second = root;
else second = root;
}
last = root;
root = root->right;
}
}
}
swap(first->val, second->val);
}
};
以上是关于leetcode-----99. 恢复二叉搜索树的主要内容,如果未能解决你的问题,请参考以下文章