题目:
题解:
func recoverTree(root *TreeNode) {var x, y, pred, predecessor *TreeNodefor root != nil {if root.Left != nil {// predecessor 节点就是当前 root 节点向左走一步,然后一直向右走至无法走为止predecessor = root.Leftfor predecessor.Right != nil && predecessor.Right != root {predecessor = predecessor.Right}// 让 predecessor 的右指针指向 root,继续遍历左子树if predecessor.Right == nil {predecessor.Right = rootroot = root.Left} else { // 说明左子树已经访问完了,我们需要断开链接if pred != nil && root.Val < pred.Val {y = rootif x == nil {x = pred}}pred = rootpredecessor.Right = nilroot = root.Right}} else { // 如果没有左孩子,则直接访问右孩子if pred != nil && root.Val < pred.Val {y = rootif x == nil {x = pred}}pred = rootroot = root.Right}}x.Val, y.Val = y.Val, x.Val
}