Java Solution with dfs / T : O(N), S : O(N)


  • 0
    J
    public boolean findTarget(TreeNode root, int k) {
            return dfs(root, k, new HashSet<Integer>());
        }
        
        public boolean dfs(TreeNode root, int k, HashSet<Integer> set) {
            if(root == null)
                return false;
            
            boolean left = dfs(root.left, k, set);
            boolean right = dfs(root.right, k, set);
            if(left || right)
                return true;
            int num2 = k-root.val;
            if(set.contains(num2))
                return true;
            set.add(root.val);
            return false;
        }
    

Log in to reply
 

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