Good! Recover-binary-search-tree (difficult) & two kinds of good space O (n) Solution & Space O (1) solution

Source: Internet
Author: User
Tags addall


https://leetcode.com/mockinterview/session/result/xyc51it/
https://leetcode.com/problems/recover-binary-search-tree/

think of the solution of Space O (N): method is to direct the BST to flatten, then reorder, and then compare it.
The original question mentioned that there is Space O (Constant) method, but also to study

Looked at the discuss, also searched the Internet, found that the space O (1) can use Morris traversal method. Wrote a separate blog, the method is described as follows:
Http://www.cnblogs.com/charlesblc/p/6013506.html

here is my answer to Leetcode's question . No O (1) space complexity is used, the O (n) spatial complexity Arrays.sort method is used, and the parameters of the ToArray function need to be noted.

In addition to this solution, there is a method that I have done before, also very good, through the two digital records may be wrong position, very ingenious, in this later given.

 PackageCom.company;ImportJava.util.*;classTreeNode {intVal;        TreeNode left;        TreeNode right; TreeNode (intX) {val =x;}}classStknode {TreeNode tn; intcount; Stknode (TreeNode tn) { This. TN =TN; Count= 0; }}classSolution {List<Integer>GetArray (TreeNode root) {List<Integer> ret =NewArraylist<>(); if(Root.left! =NULL) {Ret.addall (GetArray (root.left));        } ret.add (Root.val); if(Root.right! =NULL) {Ret.addall (GetArray (root.right)); }        returnret; }     Public voidrecovertree (TreeNode root) {//Space O (N) solution, think of is to directly put BST leveling, and then re-sort, and then compare it. //Sub-situation, left OK, right OK, 1. On OK, 2. Not OK//left not OK, or right not OK, 1. On OK,//If you don't know, use the direct method first:        if(Root = =NULL) {            return; } List<Integer> ret =GetArray (root); Integer[] Sortret= Ret.toarray (NewInteger[0]);        Arrays.sort (Sortret); int[] Change =New int[2]; int[] index =New int[2]; intII = 0;  for(inti=0; i<sortret.length; i++) {            //System.out.printf ("Old:%d, New:%d\n", Ret.get (i), sortret[i]);            if(Ret.get (i)! =Sortret[i]) {Index[ii]= I+1; CHANGE[II]=Sortret[i]; II++; if(ii >= 2) {                     Break; }            }        }        //System.out.printf ("ii:%d\n", ii);Stack<StkNode> STK =NewStack<>(); intCount = 0; intK = 0; Stknode Stkroot=NewStknode (root);        Stk.push (Stkroot);  while(!Stk.isempty ()) {Stknode tmp=Stk.pop (); //System.out.printf ("Here:%d,%d,%d\n", Tmp.count, Count, tmp.tn.val);            if(Tmp.count = = 1) {Count++; if(Count = =Index[k]) {                    //System.out.printf ("Here:%d\n", count);Tmp.tn.val =Change[k]; K++; if(k>=2) {                        return; }                }                if(Tmp.tn.right! =NULL) {Stknode newtmp=NewStknode (tmp.tn.right);                Stk.push (NEWTMP); }            }            Else{Tmp.count++;                Stk.push (TMP); if(Tmp.tn.left! =NULL) {Stknode newtmp=NewStknode (Tmp.tn.left);                Stk.push (NEWTMP); }            }        }    }} Public classMain { Public Static voidMain (string[] args) {System.out.println ("Hello!"); Solution Solution=Newsolution (); TreeNode Root=NewTreeNode (2); TreeNode Root2=NewTreeNode (3); TreeNode ROOT3=NewTreeNode (1); Root.left=Root2; Root.right=root3;        Solution.recovertree (root); System.out.printf ("Get ret: \ n"); System.out.printf ("Get Ret1:%d\n", Root.left.val); System.out.printf ("Get Ret2:%d\n", Root.val); System.out.printf ("Get Ret3:%d\n", Root.right.val);        System.out.println (); /*iterator<list<integer>> Iterator = Ret.iterator ();            while (Iterator.hasnext ()) {Iterator iter = Iterator.next (). iterator ();            while (Iter.hasnext ()) {System.out.printf ("%d,", Iter.next ());        } System.out.println (); }*/System.out.println (); }}

My previous solution, also good, is to record the possible error location by two numbers, and update the position while traversing. Need to have a deep understanding of the law of error, for example, in the solution, First_result position has not changed, because once found can be unchanged, through the Second_result position change, can meet the conditions:

Https//leetcode.com/problems/recover-binary-search-tree//*** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution {Stack< pair <treenode*,int> >Stk; Public:    voidRecovertree (treenode*root) {        if(Root = =NULL) {            return; } pair<treenode*,int> pr (root, 0);                Stk.push (PR); TreeNode* First_result =NULL; TreeNode* Last_result =NULL; TreeNode* last =NULL; Pair<treenode*,int>tmp; TreeNode*tn_tmp;  while( !Stk.empty ()) {tmp=Stk.top ();                        Stk.pop (); if(Tmp.second = = 0) {                // LeftTn_tmp =Tmp.first; Pair<treenode*,int> Tmp_cur (tn_tmp, 1);                                    Stk.push (tmp_cur); if(Tn_tmp->left! =NULL) {Pair<treenode*,int> tmp_left (tn_tmp->left, 0);                Stk.push (Tmp_left); }                            }            Else {                // RightTn_tmp =Tmp.first; if(Last! = NULL && last->val > tn_tmp->val) {                    //Found                    if(First_result = =NULL) {First_result=Last ; Last_result=tn_tmp; }                    Else{Last_result=tn_tmp;  Break; }} last=tn_tmp; if(Tn_tmp->right! =NULL) {Pair<treenode*,int> tmp_pr (tn_tmp->right, 0);                Stk.push (TMP_PR); }                            }                    }                if(First_result! = NULL && Last_result! =NULL) {            intSwap = First_result->Val; First_result->val = last_result->Val; Last_result->val =swap; }        return; }};

Good! Recover-binary-search-tree (difficult) & two kinds of good space O (n) Solution & Space O (1) solution

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.