Describe:
Elements of a binary search tree (BST) is 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.
OJ ' s Binary Tree serialization:
The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"Ideas
The first step is to traverse the binary search tree and store the traversed node in a list, then compare the values in the list, find out the two nodes where the position has changed, and swap the values of the two nodes to complete the requirement.
However, for how to find the location of the change of the two nodes is the key point and the difficulty, the specific conditions can be seen in the following procedures, and finally to find the node is also a big problem, generally meet the conditions of the judgment of the node will appear three, I take the first and the third, this is not clear, concrete can be self-elaboration
Code:
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} */public class Solution {public void Recovertree (TreeNode root) {List<treenode> ; list=new arraylist<treenode> (); if (root==null) return; Stack<treenode>st=new stack<treenode> (); St.push (root); TreeNode Top=null; while (!st.empty ()) {Top=st.peek (); while (Top.left!=null) {St.push (top.left); Top=top.left; } while (Top.right==null) {list.add (top); St.pop (); if (!st.empty ()) Top=st.peek (); else break; } if (!st.empty ()) {list.add (top); St.pop (); St.push (Top.right); }} int Len=list.size ()-1; List<integer>indexlist=new arraylist<integer> (); if (list.get (0). Val>list.get (1). val) indexlist.add (0); for (int i=1;i<len;i++) {if (List.get (i). Val<list.get (i-1).val| | List.get (i). Val>list.get (i+1). val) Indexlist.add (i); } if (List.get (len). Val<list.get (len-1). val) Indexlist.add (len); TreeNode Node1=list.get (indexlist.get (0)); TreeNode Node2=list.get (Indexlist.get (Indexlist.size ()-1)); int temp=node1.val; Node1.val=node2.val; Node2.val=temp; }}
Results:
Leetcode_99_recover Binary Search Tree