恢复二叉搜索树 (Recover Binary Search Tree)

 

思路:

// @Title: 恢复二叉搜索树 (Recover Binary Search Tree)
// @Author: qisiii
// @Date: 2024-09-17 14:41:48
// @Runtime: 1 ms
// @Memory: 43.6 MB
// @comment: 
// @flag: 
/**
 * 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 {
    TreeNode prev,next;
    List<TreeNode> errorNode=new ArrayList<>();
    public void recoverTree(TreeNode root) {
        dfs(root);
        if(errorNode.size()>1){
            next=errorNode.get(1);
        }
        int temp=errorNode.get(0).val;
        errorNode.get(0).val=next.val;
        next.val=temp;
    }
    private void dfs(TreeNode root){
        if(root==null){
            return ;
        }
        dfs(root.left);
        if(prev!=null&&root.val<prev.val){
            if(errorNode.size()==0){
                errorNode.add(prev);
                next=root;
            }else{
                errorNode.add(root);
            }
           
        }
        prev=root;
        dfs(root.right);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18