clean recursive solution, O(n) time and O(n) space


  • 1
    import java.util.HashSet;
    
    public class Solution {
        private HashSet<Integer> set = new HashSet<>();
    
        public boolean findTarget(TreeNode root, int k) {
            if (root == null) return false;
            if (set.contains(k - root.val)) return true;
            set.add(root.val);
            return findTarget(root.left, k) || findTarget(root.right, k);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.