/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode outOfOrder(TreeNode root, Comparator<Integer> cmp, int val) {
if (null == root) return null;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.addFirst(root);
TreeNode estnode = null;
while(!queue.isEmpty()) {
TreeNode node = queue.removeLast();
if (cmp.compare(node.val, val) == 1) {
if (null == estnode || cmp.compare(node.val, estnode.val) == 1)
estnode= node;
}
if (null != node.left) queue.addFirst(node.left);
if (null != node.right) queue.addFirst(node.right);
}
return estnode;
}
public void recoverTree(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == root) return;
Comparator<Integer> smaller = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2) return 1;
return 0;
}
};
Comparator<Integer> larger = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 > o2) return 1;
return 0;
}
};
TreeNode smallerNode = outOfOrder(root.right, smaller, root.val);
TreeNode largerNode = outOfOrder(root.left, larger, root.val);
if (null != smallerNode && null != largerNode) {
smallerNode.val = smallerNode.val ^ largerNode.val;
largerNode.val = smallerNode.val ^ largerNode.val;
smallerNode.val = smallerNode.val ^ largerNode.val;
} else if(null != smallerNode) {
smallerNode.val = smallerNode.val ^ root.val;
root.val = smallerNode.val ^ root.val;
smallerNode.val = smallerNode.val ^ root.val;
} else if (null != largerNode){
largerNode.val = largerNode.val ^ root.val;
root.val = largerNode.val ^ root.val;
largerNode.val = largerNode.val ^ root.val;
}
recoverTree(root.left);
recoverTree(root.right);
}
}
恢复二叉树
最新推荐文章于 2021-12-01 20:45:54 发布