99. Recover Binary Search Tree

来源:互联网 发布:淘宝店铺导航条背景色 编辑:程序博客网 时间:2024/06/05 04:39

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?

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* first;    TreeNode* second;    TreeNode* prev;    int last;    void recoverTree(TreeNode* root) {        first = NULL;        second = NULL;        prev = NULL;        last = INT_MIN;        inorder(root);        swap(first->val, second->val);    }    void inorder(TreeNode* root)    {        if(root == NULL)            return;        inorder(root->left);        if(root->val < last)        {            if(first == NULL)                first = prev;            second = root;        }        prev = root;        last = root->val;        inorder(root->right);    }};
原创粉丝点击