99.恢复二叉树
方法:
- 对二叉搜索树进行中序遍历得到值序列不满足的位置
- 找到对应被错误交换的节点记为x和y
- 交换x和y两个节点
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public void recoverTree(TreeNode root) {//定义一个数组 记录二叉搜索树的中序遍历List<Integer> num = new ArrayList<Integer>();inorder(root,num);int[] swap = findToSwapped(num);recover(root,2,swap[0],swap[1]);}public void inorder(TreeNode root,List<Integer> num){if(root == null){return;}inorder(root.left,num);num.add(root.val);inorder(root.right,num);}public int[] findToSwapped(List<Integer> num){ //排序是升序排列的,需要找到ai>ai+1和aj>aj+1对应的值int n = num.size();int index1 = -1, index2 = -1;for(int i = 0; i < n - 1 ; i++){if(num.get(i + 1) < num.get(i)){index2 = i + 1;if(index1 == -1){index1 = i;}else{break;}}}int x = num.get(index1),y = num.get(index2);return new int[]{x,y};}public void recover(TreeNode root,int count,int x,int y){if(root!=null){if(root.val == x || root.val == y){root.val = root.val == x ? y:x;if(--count==0){return;}}recover(root.left,count,x,y);recover(root.right,count,x,y);}}
}