题目链接
法一(中序遍历)
public class Solution99 {
private TreeNode first;
private TreeNode second;
private TreeNode pre;
public Solution99() {
this.first = null;
this.second = null;
this.pre = null;
}
private void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
inorderTraversal(root.left);
if (pre != null && pre.val > root.val) {
if (first == null) {
first = pre;
}
second = root;
}
pre = root;
inorderTraversal(root.right);
}
private void swap() {
if (first != null && second != null && first.val != second.val) {
first.val ^= second.val;
second.val ^= first.val;
first.val ^= second.val;
}
}
public void recoverTree(TreeNode root) {
inorderTraversal(root);
swap();
}
}
本地测试
lay.showTitle(99);
Solution99 sol99 = new Solution99();
List<Integer> arr99 = Arrays.asList(3, 1, 4, null, null, 2);
TreeNode root99 = treeOpt.createTreeByLayerOrder(arr99);
treeOpt.layerOrder(root99);
sol99.recoverTree(root99);
treeOpt.layerOrder(root99);