LeetCode: Recover Binary Search Tree

来源:互联网 发布:阿尔及利亚地图软件 编辑:程序博客网 时间:2024/04/30 00:44

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 binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void recoverTree(TreeNode *root) {        inOrder(root);        int temp = first->val;        first->val = second->val;        second->val = temp;    }  private:TreeNode *first;TreeNode *second;TreeNode *pre;    void inOrder(TreeNode* root)    {        if(root == NULL)            return;        inOrder(root->left);        if(pre == NULL)            pre = root;        else        {            if(root-> val <= pre->val)            {                if(first == NULL)                    first = pre;                second = root;            }            pre = root;        }                inOrder(root->right);            }};

Round 2:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void recoverTree(TreeNode *root) {        TreeNode *first = NULL, *second = NULL, *pre = NULL;        inorder(root, &first, &second, &pre);        int temp = first->val;        first->val = second->val;        second->val = temp;            }private:    void inorder(TreeNode* root, TreeNode **first, TreeNode **second, TreeNode **pre)    {        if(root == NULL)            return;        inorder(root->left, first, second, pre);        if(*pre == NULL)        {            *pre = root;        }        else        {            if(root->val <= (*pre)->val)            {                if(*first == NULL)                    *first = *pre;                *second = root;            }            *pre = root;        }        inorder(root->right, first, second, pre);    }};


0 0