The bst(binary search tree)'s inorder traverse is ascend. In the following solution, I created an assistant point to record current subtree’s root’s pre nodes in inorder traverse. The key point here is that exactly two nodes were swapped. which could result in one or two inverse pairs. Suppose the sequence is a1,a2, …, an and ai, aj which is in the sequence is the inverse pair nodes, and if ai is next to aj, only one inverse pair <ai, aj> will be found, and when ai isn’t next to aj, two inverse pairs would be found, which is <ai, ai+1> and <aj-1, aj> (i < j). So in the swap function, when I find the first inverse pair, I just save it and when I found a second inverse pair, I exchange ai and aj which is a[0] and root to recover the tree. And if I don’t find a second inverse pair, I can now make a conclusion that ai is next to aj, so I just need to exchange a[0] and a[1] which is exactly ai and aj. And the time complexity is the same as space complexity which is O(n).
func swap(pre **TreeNode, root *TreeNode, a []*TreeNode, exchanged *bool){
if (*pre)!=nil{
if (*pre).Val < root.Val{
//normal
}else{
if a[0]==nil {
a[0]=*pre
a[1]=root
}else{
temp:=root.Val
root.Val=a[0].Val
a[0].Val=temp
(*exchanged)=true
}
}
}
}
func fakeRecoverTree(pre **TreeNode, root *TreeNode, a []*TreeNode, exchanged *bool) {
if root==nil{
return
}
fakeRecoverTree(pre,root.Left,a,exchanged)
swap(pre,root,a,exchanged)
*pre=root
fakeRecoverTree(pre,root.Right,a,exchanged)
}
func recoverTree(root *TreeNode) {
var a []*TreeNode = []*TreeNode{nil,nil}
var pre *TreeNode = nil
var exchanged bool=false
fakeRecoverTree(&pre,root,a,&exchanged)
if !exchanged&&a[1]!=nil{
temp:=a[1].Val
a[1].Val=a[0].Val
a[0].Val=temp
}
}