本题不算非常难,想明白后就是介于Easy和Medium之间。。但是第一次做比较难作出完美的抽象,所以非常值得学习。。
首先,我们需要“忘掉”这是个Tree,要想像成一个sorted array,比如:[1, 2, 3, 4, 5, 6]
- 一个Binary Search Tree,只有做inorder traversal就会打印出sorted array
- Two element of BST are swapped by mistake,可以理解成数组中的两个元素swap:
[1, 2, 4, 3, 5, 6]
: 相邻元素swap,即只有一次[1, 6, 3, 4, 5, 2]
: 不相邻元素swap,此时有两次,分别找到即可
本题一点也不难,代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode prev;
private TreeNode first;
private TreeNode second;
public void recoverTree(TreeNode root) {
inorder(root);
int val = first.val;
first.val = second.val;
second.val = val;
}
private void inorder(TreeNode node) {
if (node.left != null) {
inorder(node.left);
}
if (prev != null && node.val < prev.val ) {
if (first == null) {
first = prev;
}
if (first != null) {
second = node;
}
}
prev = node;
if (node.right != null) {
inorder(node.right);
}
}
}