[leetcode] 99. Recover Binary Search Tree 解题报告

题目链接:https://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.


思路:可以用递归实现O(n)空间复杂度的方法,这几天好浮躁,等我下次再来写O(1)的实现的吧。睡觉

代码如下:

/**
 * 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:
    void inOrder(TreeNode* root)
    {
        if(!root) return;
        inOrder(root->left);
        if(pre)
        {
            if(pre->val > root->val)
            {
                if(!first)
                    first = pre;
                second = root;
            }
        }
        pre = root;
        inOrder(root->right);
    }
    void recoverTree(TreeNode* root) {
        if(!root) return;
        first = NULL, second = NULL, pre = NULL;
        int tem;
        inOrder(root);
        tem = first->val;
        first->val = second->val;
        second->val = tem;
    }
private:
    TreeNode *first, *second, *pre;
};

参考:不知道哪个博客了,昨天做的这题,本来还想继续写O(1)的算法,噢!已经开始正式上课了,我必须要尽快刷完leetcode!不然就没时间了!开放的题目目前有250+左右,我还有70+的题目没做,希望这个月底能做完!

你可能感兴趣的:(LeetCode,tree,binary)