Advertisement
K_S_

Untitled

Oct 31st, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. // Runtime: 2 ms, faster than 95.13% of Java online submissions for Two Sum IV - Input is a BST.
  2. // Memory Usage: 41.9 MB, less than 69.64% of Java online submissions for Two Sum IV - Input is a BST.
  3.  
  4. class Solution {
  5.     public boolean findTarget(TreeNode root, int k) {
  6.         Queue<TreeNode> q = new ArrayDeque<>();
  7.         q.add(root);
  8.  
  9.         while (!q.isEmpty()) {
  10.             TreeNode node = q.remove();
  11.             int val = node.val;
  12.             int diff = k - val;
  13.             if (exists(node, root, diff)) {
  14.                 return true;
  15.             }
  16.             if (node.left != null) {
  17.                 q.add(node.left);
  18.             }
  19.             if (node.right != null) {
  20.                 q.add(node.right);
  21.             }
  22.         }
  23.  
  24.         return false;
  25.     }
  26.  
  27.     private boolean exists(TreeNode curr, TreeNode node, int val) {
  28.         if(node == null) {
  29.             return false;
  30.         }
  31.  
  32.         if(node != curr) {
  33.             if(node.val == val) {
  34.                 return true;
  35.             }
  36.         }
  37.         if(node.val > val) {
  38.             return exists(curr, node.left, val);
  39.         } else {
  40.             return exists(curr, node.right, val);
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement