99. Recover Binary Search Tree

来源:互联网 发布:托福阅读满分 知乎 编辑:程序博客网 时间:2024/06/04 19:36
  1. 问题描述
    wo 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?
    Subscribe to see which companies asked this question.

  2. 解决思路
    使用inorder遍历的办法,因为在二叉查询树时,inorder遍历会满足遍历到的节点是有序的,而此时为升序,所以我们只要找到两个不满足pre->val < cur->val的节点就可以了。

  3. 代码

/** * 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=NULL;    TreeNode* second=NULL;    TreeNode* pre = new TreeNode(INT_MIN);    void recoverTree(TreeNode* root) {        helper(root);        int tmp = first->val;        first->val = second->val;        second->val = tmp;    }    void helper(TreeNode* root) {        if (root == NULL)            return;        helper(root->left);        if (!first && pre->val >= root->val) first = pre;        if (first && pre->val >= root->val) {second = root; }        pre = root;        helper(root->right);    }};
0 0