/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassSolution{ publicbooleanfindTarget(TreeNode root, int k){ Map<Integer, Integer> dict = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<>(); queue.add(root);
while (!queue.isEmpty()) { TreeNode node = queue.poll(); dict.put(node.val, dict.getOrDefault(node.val, 0) + 1); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); }
for (Map.Entry<Integer, Integer> entry : dict.entrySet()) { int val = entry.getKey(); int tar = k - val; if (val == tar && entry.getValue() > 1) returntrue; if (val != tar && dict.containsKey(tar)) returntrue;