二叉樹的路徑和(沒必要以根節點爲起始)Path Sum III

問題:node

You are given a binary tree in which each node contains an integer value.spa

Find the number of paths that sum to a given value.get

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).it

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.io

Example:class

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

解決:二叉樹

① 這道題就是給了一個二叉樹和一個目標和sum,找出全部路徑,這個路徑的和等於sum,只容許從父節點到子節點的路線。使用DFS(Dpeth-first Search,深度優先搜索)查找知足條件的路徑。搜索

/**  *遍歷

 Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {//30ms
    public int pathSum(TreeNode root, int sum) {
        if(root == null) //必須判斷,不然會越界
            return 0;
        return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
    }
    private int dfs(TreeNode root, int sum){
        int count = 0;
        if(root == null)
            return count;
        if(sum == root.val)
            count ++;
        count += dfs(root.left,sum - root.val);
        count += dfs(root.right,sum - root.val);
        return count;
    }
}map

② 用map記錄當前遍歷路徑中的子路徑權值和對應出現的次數

1. sum表示從根節點到某節點X,路徑的權值和,則遍歷至X節點時,當前的路徑和curSum剛好與sum相等,此時count = map.getOrDefault(curSum - target,0) = map.get(0) = 1;

2. 若sum爲某段子路徑的權值和,如:x1->x2->x3->x4......中sum等於節點x3與節點x4的權值和,即sum = sum(x3+x4)。則遍歷至x2時, m[curSum]++; 處已經記錄了m[curSum] = m[sum(x1+x2)] = 1,遍歷至x4時curSum = sum(x1+x2+x3+x4),則res = m[curSum - sum] = m[sum(x1+x2+x3+x4) - sum(x3+x4)] = m[sum(x1+x2)] = 1。

public class Solution {//26ms     public int pathSum(TreeNode root, int sum) {         Map<Integer,Integer> map = new HashMap<Integer,Integer>();//map(curSum,個數)         map.put(0,1);//初始權值爲0,個數爲1         return dfs(root,sum,map,0);        }     public int dfs(TreeNode root,int sum,Map<Integer,Integer> map,int curSum){         if(root == null) return 0;         curSum += root.val;         int count = map.getOrDefault(curSum - sum,0);//獲取當前子節點包含權值爲 sum的子段的個數         map.put(curSum,map.getOrDefault(curSum,0) + 1);//記錄當前子節點權值的個數加1         count += dfs(root.left,sum,map,curSum) + dfs(root.right,sum,map,curSum);         map.put(curSum,map.get(curSum) - 1);         return count;        } }

相關文章
相關標籤/搜索