437 Path Sum III (Find the number of paths that sum to a given value.)
Path Sum III Solution 1 : Typical recursive DFS. Space: O(n) due to recursion. Time: O(n^2) in worst case (no branching); O(nlogn) in best case (balanced tree). https://leetcode.com/problems/path-sum-iii/discuss/91889/Simple-Java-DFS class Solution { public int pathSum(TreeNode root, int sum) { // base case if(root == null){ return 0; } // recursion + induction rule return helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } private int helper(TreeNode root, int sum){ int count = 0; // base case if(root == null) return count; // recursion + induction rule if(root.val == sum) count++; int left = helper(root.left, sum - root.val); int right = helper(root.right, sum - root.val); count = count + left + right; return count; } } This code is elegant but very inefficient. During an interview, you'll be asked 'how can we improve the runtime performance'? And you better be able to give the prefix sum solution which does it in O(N) Solution 2 : https://leetcode.com/problems/path-sum-iii/discuss/91878/17-ms-O(n)-java-Prefix-sum-method // The time complexity is O(n). class Solution { int count = 0; public int pathSum(TreeNode root, int sum) { HashMap<Integer, Integer> preSum = new HashMap(); preSum.put(0, 1); helper(root, 0, sum, preSum); return count; } public void helper(TreeNode root, int curSum, int target, HashMap<Integer, Integer> preSum){ if(root == null){ return; } curSum += root.val; // whenever reach a node, we check if curSum - target exists in hashmap or not, if it does, we added up the ways of curaum - target into res. if(preSum.containsKey(curSum - target)){ count += preSum.get(curSum - target); } // add the cursum to the hashmap if(!preSum.containsKey(curSum)){ preSum.put(curSum, 1); }else{ preSum.put(curSum, preSum.get(curSum) + 1); } helper(root.left, curSum, target, preSum); helper(root.right, curSum, target, preSum); // backtracking preSum.put(curSum, preSum.get(curSum) - 1); } }
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
posted on 2018-08-10 14:48 猪猪🐷 阅读(123) 评论(0) 收藏 举报
浙公网安备 33010602011771号