/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*采用Morris遍历的方法,用以确定两个被打乱的地方。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
void recoverTree(TreeNode* root) {
//if(root == nullptr || (root->left == nullptr && root->right == nullptr))
// return;
TreeNode *first(nullptr), *second(nullptr);
TreeNode *pre(nullptr), *cur(root);
while(cur != nullptr){
if(cur->left == nullptr){//无左子树,访问该节点
detect(&first, &second, pre, cur);
pre = cur;
cur = cur->right;
}
else{//找到左子树最右的叶子节点,并将它作为当前节点前驱
TreeNode *p = cur->left;
while(p->right != nullptr && p->right != cur) p = p->right;
if(p->right == nullptr){//构造线索
p->right = cur;
cur = cur->left;
}
else{//对它进行访问
detect(&first, &second, pre, cur);
p->right = nullptr;
pre = cur;
cur = cur->right;
}
}
}
swap(first->val, second->val);
}
void detect(TreeNode **first, TreeNode **second, TreeNode *pre, TreeNode *cur){
if(pre != nullptr && pre->val > cur->val){
if(*first == nullptr) *first = pre;
*second = cur;
}
}
};
LeetCode之Recover Binary Search Tree
最新推荐文章于 2019-05-27 12:46:09 发布