Leetcode-Recover Binary Search Tree

Source: Internet
Author: User

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. cocould you devise a constant space solution?

Confused what"{1,#,2,3}"Means? > Read more on how binary tree is serialized on OJ.

The question is that two nodes in a binary search tree are incorrectly exchanged and the structure of the tree is not changed to restore the normal binary search tree.

Solution 1:

The solution to the space complexity of O (n) is relatively easy. We can assign a value to the array by traversing the binary search tree in the middle order, and then directly scan the array element to record the position in the reverse order, the logarithm of the reverse order may have one or two pairs. Assume that the elements are sorted in order of 1, 2, 3, 4, and 5.

For example, values of 1, 2, 4, 3, and 5 can be directly exchanged between values of 4 and 3. If there are two pairs, such as 1, 5, 3, 4, and 2, we can find the elements 5 and 2 in the reverse order, and exchange them with 5 and 2.

But how can we exchange nodes in a binary tree based on this information? We can store the ing between element values and tree node pointers, and use STL map containers. key is the element value, and value is the node pointer.

The Code is as follows:

/** * 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) {        vector
 
   v;        map
  
    mm;        //inorder         stack
   
     s;        s.push(root);        while (!s.empty()) {            TreeNode *tmp = s.top();            while (tmp->left!=NULL) {                s.push(tmp->left);                tmp = tmp->left;            }            v.push_back(tmp->val);            mm[tmp->val] = tmp;            s.pop();            while (tmp->right==NULL && !s.empty()) {                tmp = s.top();                v.push_back(tmp->val);                mm[tmp->val] = tmp;                s.pop();            }            if (tmp->right!=NULL)                s.push(tmp->right);        }        int p1=-1, p2 = -1;        for (int i=1; i
    
     val, mm[v[p1+1]]->val);        } else {            swap(mm[v[p1]]->val, mm[v[p2+1]]->val);        }    }private:    void swap(int &a, int &b) {        int tmp = a;        a = b;        b = tmp;    }};
    
   
  
 

Solution 2:

Considering the nature of the Binary Search Tree, two node values may be exchanged. One is that the root node values are exchanged between the left and right nodes, second, the root node value is exchanged with a node value on the left subtree. Third, the root node value is exchanged with a node on the right subtree, 4. The two nodes in the left or right subtree are exchanged.

In this case, we can find a node value greater than the root node value in the left subtree and a node value smaller than the root node value in the right subtree, then exchange the values of the two nodes found;

In Case 2, we need to find the node with the largest value than the root node in the left subtree, and then exchange the root node and find the value of the node;

In case 3, we need to find the node with the smallest value than the root node in the right subtree, and then exchange the root node and find the node value;

In case 4, we call this operation recursively on the left and right subtree of the root node.

/*** 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) {if (root = NULL) return; // find the maximum node TreeNode * leftBiggest = root; find (root-> left, leftBiggest, "largest") of the left subtree "); // find the minimum node TreeNode * rightSmallest = root; find (root-> right, rig HtSmallest, "smallest"); // The two left and right children of root mistakenly exchanged if (leftBiggest! = Root & rightSmallest! = Root) {swap (leftBiggest-> val, rightSmallest-> val);} else if (leftBiggest! = Root) {// The right subtree is normal. root and leftBiggest mistakenly exchanged swap (root-> val, leftBiggest-> val);} else if (rightSmallest! = Root) {// The left subtree is normal. The root and rightSmallest mistakenly exchanged swap (root-> val, rightSmallest-> val );} else {// two nodes in the left or right subtree mistakenly exchange recoverTree (root-> left); recoverTree (root-> right);} private: void find (TreeNode * root, TreeNode * & p, const string & relation) {if (root = NULL) return; if (relation = "smallest" & root-> val
 
  
Val) p = root; else if (relation = "largest" & root-> val> p-> val) p = root; find (root-> left, p, relation); find (root-> right, p, relation);} void swap (int & a, int & B) {int tmp = a; a = B; B = tmp ;}};
 





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.