Leetcode:Recover Binary Search Tree 恢复BST 交换两结点值

Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

 

 

解题分析:

BST的中序序列一定是一个 非递减序列,我们可以从这一性质入手

1.首先中序遍历BST

2.从头开始寻找第一个逆序结点

3.从尾开始寻找第二个逆序结点

4. swap结点值

class Solution {
public:
    void recoverTree(TreeNode *root) {
        if (root == nullptr) return;
        vector<TreeNode*> result;
        inorder(root, result);
        TreeNode* first = nullptr;
        TreeNode* last = nullptr;
        for (int i = 0; i < result.size() - 1; ++i) {
            if (result.at(i)->val > result.at(i+1)->val) {
                first = result.at(i);
                break;
            }
        }
        for (int i = result.size() - 1; i > 0; --i) {
            if (result.at(i)->val < result.at(i-1)->val) {
                last = result.at(i);
                break;
            }
        }
        swap(first->val, last->val);
    }
    
    void inorder(TreeNode* root, vector<TreeNode*>& result) {
        if (root == nullptr) return;
        inorder(root->left, result);
        result.push_back(root);
        inorder(root->right, result);
    }
};

 

Update:

题目要求 O(1)空间,我们知道 二叉树遍历一般有 递归法、非递归(使用栈)、非递归(不使用栈) 即 Morris线索遍历

详见:http://www.cnblogs.com/wwwjieo0/p/3624011.html

你可能感兴趣的:(Binary search)