My simple java code

  • 0

    The idea is to carry a set of the elements you have traversed so far and check if (sum-currentElement) exists in the set. Time and space complexity is O(n)

    public boolean helper(TreeNode root, HashSet<Integer> set, int k){
            if (root == null) return false;
            if (set.contains(k - root.val)) return true;
            return helper(root.left, set, k) || helper(root.right, set, k);
        public boolean findTarget(TreeNode root, int k) {
            HashSet<Integer> set = new HashSet<Integer>();
            return helper(root, set, k);      

Log in to reply

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