【LeetCode刷题-树】-- 99.恢复二叉树

99.恢复二叉树

image-20231211095657561

方法:

  • 对二叉搜索树进行中序遍历得到值序列不满足的位置
  • 找到对应被错误交换的节点记为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);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值