题目描述:
代码实现:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var recoverTree = function(root) {
if (!root) {
return null
}
var curr = root
var node1 = null
var node2 = null
var lastNode = null
while (curr) {
if (curr.left) {
var preNode = curr.left
while (preNode.right && preNode.right != curr) {
preNode = preNode.right
}
if (!preNode.right) {
preNode.right = curr
curr = curr.left
} else {
if (lastNode && lastNode.val > curr.val) {
if (node1) {
node2 = curr
} else {
node1 = lastNode
node2 = curr
}
}
lastNode = curr
curr = curr.right
preNode.right = null
}
} else {
if (lastNode && lastNode.val > curr.val) {
if (node1) {
node2 = curr
} else {
node1 = lastNode
node2 = curr
}
}
lastNode = curr
curr = curr.right
}
}
const tmp = node1.val
node1.val = node2.val
node2.val = tmp
};