[leetcode]99. Recover Binary Search Tree

来源:互联网 发布:怎样成为网络歌手软件 编辑:程序博客网 时间:2024/05/16 17:28

题目链接:https://leetcode.com/problems/recover-binary-search-tree/#/description

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

Recover the tree without changing its structure.

题目有一个附加要求就是要求空间复杂度为常数空间。而算法一的空间复杂度为O(N),还不够省空间。以下的解法也是中序遍历的写法,只是非常巧妙,使用了一个prev指针。例如一颗被破坏的二叉查找树如下:

        4

       /     \

              2        6

                /   \    /   \

               1    5  3    7

很明显3和5颠倒了。那么在中序遍历时:当碰到第一个逆序时:为5->4,那么将n1指向5,n2指向4,注意,此时n1已经确定下来了。然后prev和root一直向后遍历,直到碰到第二个逆序时:4->3,此时将n2指向3,那么n1和n2都已经确定,只需要交换节点的值即可。prev指针用来比较中序遍历中相邻两个值的大小关系,很巧妙。


class Solution {public:    void recoverTree(TreeNode* root) {        help(root);        swap(first->val, second->val);    }    void help(TreeNode* root){        if(root==NULL)  return;        help(root->left);        if(first==NULL && prev->val >= root->val)   first=prev;        if(first!=NULL && prev->val >= root->val)   second=root;        prev=root;        help(root->right);    }private:    TreeNode* first=NULL;    TreeNode* second=NULL;    TreeNode* prev = new TreeNode(INT32_MIN);};



原创粉丝点击