Easy to understand solution using HashMap


  • 0
    Z
    class Solution {
        public boolean findTarget(TreeNode root, int k) {
            if(root == null) return false;
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            map.put(k-root.val, root.val);
            return work(root.left, k, map) || work(root.right, k, map);
            
        }
        public boolean work(TreeNode root, int k, Map<Integer, Integer> map){
            if(root == null) return false;
            if(map.containsKey(root.val)){
                return true;
            }else{
                map.put(k-root.val, root.val);
                return work(root.left, k, map) || work(root.right, k, map);
            }
            
        }
    }
    

Log in to reply
 

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