/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcrecoverTree(root*TreeNode){vararr[]intvarinorderfunc(root*TreeNode)inorder=func(root*TreeNode){ifnil==root{return}inorder(root.Left)arr=append(arr,root.Val)inorder(root.Right)}inorder(root)a,b:=-1,-1fori:=0;i<len(arr)-1;i++{ifarr[i]>arr[i+1]{ifa==-1{a=i}else{b=i+1}}}ifb==-1{b=a+1}x,y:=arr[a],arr[b]varfixfunc(root*TreeNode)fix=func(root*TreeNode){ifnil==root{return}ifroot.Val==x{root.Val=y}elseifroot.Val==y{root.Val=x}fix(root.Left)fix(root.Right)}fix(root)}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcrecoverTree(root*TreeNode){vararr[]intvarinorderfunc(root*TreeNode)inorder=func(root*TreeNode){ifnil==root{return}inorder(root.Left)arr=append(arr,root.Val)inorder(root.Right)}inorder(root)a,b:=-1,-1fori:=0;i<len(arr)-1;i++{ifarr[i]>arr[i+1]{ifa==-1{a=ib=a+1// 直接更新 b
}else{b=i+1}}}x,y:=arr[a],arr[b]varfixfunc(root*TreeNode)fix=func(root*TreeNode){ifnil==root{return}ifroot.Val==x{root.Val=y}elseifroot.Val==y{root.Val=x}fix(root.Left)fix(root.Right)}fix(root)}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcrecoverTree(root*TreeNode){varprev,nodeA,nodeB*TreeNodevarinorderfunc(root*TreeNode)inorder=func(root*TreeNode){ifnil==root{return}inorder(root.Left)ifnil!=prev{ifprev.Val>root.Val{ifnil==nodeA{nodeA=prevnodeB=root}else{nodeB=root}}}prev=rootinorder(root.Right)}inorder(root)nodeA.Val,nodeB.Val=nodeB.Val,nodeA.Val}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcrecoverTree(root*TreeNode){varprev,nodeA,nodeB*TreeNodecur:=rootfornil!=cur{ifnil!=cur.Left{mostRight:=cur.Leftfornil!=mostRight.Right&&cur!=mostRight.Right{mostRight=mostRight.Right}ifnil==mostRight.Right{mostRight.Right=curcur=cur.Leftcontinue}else{// cur == mostRight.Right
mostRight.Right=nilifnil!=prev{ifprev.Val>cur.Val{ifnil==nodeA{nodeA=prevnodeB=cur}else{nodeB=cur}}}prev=cur// 已经遍历完左子树,转到右子树
cur=cur.Right}}else{ifnil!=prev{ifprev.Val>cur.Val{ifnil==nodeA{nodeA=prevnodeB=cur}else{nodeB=cur}}}prev=cur// 转到右子树
cur=cur.Right}}nodeA.Val,nodeB.Val=nodeB.Val,nodeA.Val}