Leetcode_recover-binary-search-tree

来源:互联网 发布:数据上限下限设定 编辑:程序博客网 时间:2024/06/14 01:55
地址:http://oj.leetcode.com/problems/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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

思路:根据二叉查找树的中序遍历是升序来确定交换的两个节点。
既然有两个节点被交换,那么在中序遍历中,就是“前面”的值较小的节点与“后面”的值较大的节点交换。
那么顺藤摸瓜,第一次找“较大”节点,第二次找“较小”节点。
假定x1, x2, x3, x4, ,,,,xn-1, xn 是树的中序遍历,若开始我们发现Xk > Xk+1, 用sw1 存储Xk, sw2存储Xk+1, 其中sw1就是我们所谓的“较大”节点值。这个时候存储sw2是因为有可能被交换的节点在中序的序列中是相邻的。然后我们再遍历下去,如有又发现Xt > Xt+1, 那么我们就肯定Xt+1就是我们要找的“较小”节点值。这个时候交换Xk与Xt+1的值就OK了。
参考代码:
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode*lastNode = NULL, *sw1 = NULL, *sw2 = NULL;    void in_order_tra(TreeNode* root)    {        if(root->left)            in_order_tra(root->left);        if(lastNode)        {            if(lastNode->val > root->val)            {                if(!sw1)                {                    sw1 = lastNode;                    sw2 = root;                }                else                {                    sw2 = root;                    return;                }            }        }        lastNode = root;        if(root->right)            in_order_tra(root->right);    }    void recoverTree(TreeNode *root) {        if(!root)            return;        in_order_tra(root);        if(sw1 && sw2)            swap(sw1->val, sw2->val);    }};


0 0