ogv

Untitled

ogv
Oct 31st, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. // Runtime: 1 ms, faster than 100.00% of Java online submissions for Two Sum IV - Input is a BST.
  2. class Solution {
  3.     TreeNode root;
  4.    
  5.     public boolean findTarget(TreeNode root, int k) {
  6.         this.root = root;
  7.         return findSum(root, k);
  8.     }
  9.    
  10.     private boolean findSum(TreeNode current, int target) {
  11.         if (current == null) return false;
  12.        
  13.         if (find(root, target - current.val, current)) return true;
  14.         if (findSum(current.left, target)) return true;
  15.         if (findSum(current.right, target)) return true;
  16.         return false;
  17.     }
  18.    
  19.     private boolean find(TreeNode current, int target, TreeNode stopNode) {
  20.         if (current == null) return false;
  21.        
  22.         if (current != stopNode && current.val == target) return true;
  23.         else if (target < current.val) return find(current.left, target, stopNode);
  24.         else return find(current.right, target, stopNode);
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment