leetcode99 恢复二叉搜索树

给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。

进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?

示例 1:
image

链接:https://leetcode-cn.com/problems/recover-binary-search-tree

树上节点的数目在范围 [2, 1000] 内
-231 <= Node.val <= 231 - 1
/**
 * 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 {
     ArrayList<Integer> orders=new ArrayList<>();
    public void recoverTree(TreeNode root) {
        InorderTraversal(root,orders);
        
        reverse(root,findtwoNum());
    }
    public void InorderTraversal(TreeNode root,ArrayList<Integer>orders)
    {
        if(root==null)
        {
            return;
        }
        InorderTraversal(root.left,orders);
        orders.add(root.val);
        InorderTraversal(root.right,orders);
    }
    
   public int[] findtwoNum()
    {
        int[] arr=new int[2];
        int count=0;
        int index=0;
        for(int i=0;i<orders.size()-1;i++)
        {
            if(orders.get(i)>orders.get(i+1))
            {
                if(count==0)
                {
                    arr[0]=orders.get(i);
                    index=i;
                    arr[1]=orders.get(i+1);
                    count++;
                }else {
                    arr[1]=orders.get(i+1);
                    count++;
                }
            }
        
        }
       
      
        return arr;
    }

    public void reverse(TreeNode root,int[] arr)
    {
        if(root==null)
        {
            return;
        }
        root.val=root.val==arr[0]?arr[1]:root.val==arr[1]?arr[0]:root.val;
        reverse(root.left,arr);
        reverse(root.right,arr);
    }
}
posted @ 2021-08-23 10:33  LiangLiangAA  阅读(35)  评论(0编辑  收藏  举报
theme: { name: 'geek', avatar: '', headerBackground: '' // ... },