Correct a Binary Tree

给一个二叉树, 其中有一个node是invalid, 这种invalid是他的右子树连到了右边的任意node. 求删除这个错误的子树后的树.

这个题主要是读懂题, 理解这种invalid只能发生在某个node的右子树上. 然后查重要用set. 就没了

/**
 * 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 {
    Set<TreeNode> set = new HashSet<>();
    public TreeNode correctBinaryTree(TreeNode root) {
        if(root == null)
            return root;
        if(root.right != null) {
            if(root.right.right != null && set.contains(root.right.right)) {
                root.right = null;
                return root;
            }
            else{
                set.add(root.right);
                correctBinaryTree(root.right);
            }
        }
        if(root.left != null) {
            if(root.left.right != null && set.contains(root.left.right)) {
                root.left = null;
                return root;
            }
            else{
                set.add(root.left);
                correctBinaryTree(root.left);
            }
        }
        return root;
    }
}