码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-----99. 恢复二叉搜索树

时间:2020-07-19 11:36:41      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:链接   node   bin   sea   代码   arc   ast   tree node   val   

代码

/**
 * 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. 恢复二叉搜索树

标签:链接   node   bin   sea   代码   arc   ast   tree node   val   

原文地址:https://www.cnblogs.com/clown9804/p/13338817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!