Sunday, January 22, 2017

Leetcode -- 437. Path Sum III (2DFS)

437. Path Sum III
Easy
https://leetcode.com/problems/path-sum-iii/
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
思路: do two recursion. different from pathSumII that start can be any node, so we have 1st recur.
1st: recursively travel tree to find answers of current node + ans of left child + ans of right child.
2nd: find the path from current node to child that adds up to sum
Complexity: 
If the tree is balanced, then each node is reached from its ancestors (+ itself) only, which are up to log n. Thus, the time complexity for a balanced tree is O (n * log n).
However, in the worst-case scenario where the binary tree has the same structure as a linked list, the time complexity is indeed O (n ^ 2)
O(H) space - height of binary tree

public class Solution {
    public int pathSum(TreeNode root, int sum) {
        if (root == null)return 0;
        return helper(root,sum) + pathSum(root.left,sum) + pathSum(root.right,sum);
        //so total count will be countOf(hasRoot) + countOf(leftChild) + countOf(rightChild) 
    }
    public int helper(TreeNode root,int sum){
        int count  = 0;
        if(root == null)return 0;
        if(root.val - sum == 0)count++;
        count += helper(root.left, sum - root.val);
        count += helper(root.right, sum - root.val);
        return count;
    }
}
 

Version2 more comprehensive
public class Solution {
    int count = 0;
    public int pathSum(TreeNode root, int sum) {
        if (root == null)return 0;
        helper(root,sum);
        pathSum(root.left,sum);
        pathSum(root.right,sum);
        return count;
    }
    public void helper(TreeNode root,int sum){
        if(root == null)return;
        if(root.val - sum == 0)count++;
        helper(root.left, sum - root.val);
        helper(root.right, sum - root.val);
    }
}


          

No comments:

Post a Comment