Advertisement
sweet1cris

Untitled

Sep 25th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.03 KB | None | 0 0
  1. public class BinaryTreePathSumToTarget {
  2.   public boolean exist(TreeNode root, int sum) {
  3.     if (root == null) {
  4.       return false;
  5.     }
  6.     // pass down the prefix of the path.
  7.     List<TreeNode> path = new ArrayList<TreeNode>();
  8.     return helper(root, path, sum);
  9.  
  10.   }
  11.  
  12.   private boolean helper(TreeNode root, List<TreeNode> path, int sum) {
  13.     path.add(root);
  14.     // check if can find a subpath ended at root node,
  15.     // the sum of the subpath is target.
  16.     int tmp = 0;
  17.     for (int i = path.size() - 1; i >= 0; i--) {
  18.       tmp += path.get(i).key;
  19.       if (tmp == sum) {
  20.         return true;
  21.       }
  22.     }
  23.     if (root.left != null && helper(root.left, path, sum)) {
  24.       return true;
  25.     }
  26.     if (root.right != null && helper(root.right, path, sum)) {
  27.       return true;
  28.     }
  29.     // don't forget for the cleanup when return to the previous level.
  30.     path.remove(path.size() - 1);
  31.     return false;
  32.   }
  33.  
  34.   // Method 2: an O(n) solution.
  35.   // Think about the related problem, how do you find if there is
  36.   // a subarray sum to target value
  37.   // If there is an O(n) solution to the above problem, we can extend
  38.   // it to each of the root->leaf paths of the binary tree.
  39.   public boolean existII(TreeNode root, int sum) {
  40.     if (root == null) {
  41.       return false;
  42.     }
  43.     Set<Integer> prefixSums = new HashSet<>();
  44.     prefixSums.add(0);
  45.     return helperII(root, prefixSums, 0, sum);
  46.   }
  47.  
  48.   private boolean helperII(TreeNode root, Set<Integer> prefixSums, int prevSum,
  49. int sum) {
  50.     prevSum += root.key;
  51.     if (prefixSums.contains(prevSum - sum)) {
  52.       return true;
  53.     }
  54.     boolean needRemove = prefixSums.add(prevSum);
  55.     if (root.left != null && helperII(root.left, prefixSums, prevSum, sum)) {
  56.       return true;
  57.     }
  58.  
  59.  
  60.     if (root.right != null && helperII(root.right, prefixSums, prevSum, sum)) {
  61.       return true;
  62.     }
  63.     if (needRemove) {
  64.       prefixSums.remove(prevSum);
  65.     }
  66.     return false;
  67.   }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement