LeetCode: 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?

O(n)的空间,constant space solution以后再想。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void recoverTree(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) return;
        vector<TreeNode*> inorder;
        stack<TreeNode*> stk;
        TreeNode* p = root;
        do
        {
            if (p != NULL)
            {
                stk.push(p);
                p = p->left;
            }
            else
            {
                p = stk.top();
                stk.pop();
                inorder.push_back(p);
                p = p->right;
            }
        }while(!stk.empty() || p != NULL);
        
        int first, second;
        for (int i = 0; i < inorder.size()-1; ++i)
        {
            if (inorder[i]->val > inorder[i+1]->val)
            {
                first = i;
                break;
            }
        }
        
        for (int i = inorder.size()-1; i > 0; --i)
        {
            if (inorder[i]->val < inorder[i-1]->val)
            {
                second = i;
                break;
            }
        }
        
        int tmp = inorder[first]->val;
        inorder[first]->val = inorder[second]->val;
        inorder[second]->val = tmp;
    }
};

点赞