leetcode面试题 04.12. 求和路径(dfs)
生活随笔
收集整理的這篇文章主要介紹了
leetcode面试题 04.12. 求和路径(dfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一棵二叉樹,其中每個節點都含有一個整數數值(該值或正或負)。設計一個算法,打印節點數值總和等于某個給定值的所有路徑的數量。注意,路徑不一定非得從二叉樹的根節點或葉節點開始或結束,但是其方向必須向下(只能從父節點指向子節點方向)。示例:
給定如下二叉樹,以及目標和 sum = 22,5/ \4 8/ / \11 13 4/ \ / \7 2 5 1
返回:3
解釋:和為 22 的路徑有:[5,4,11,2], [5,8,4,5], [4,11,7]
代碼
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {int tar, cnt = 0;public int pathSum(TreeNode root, int sum) {tar = sum;Sum(root, 0, new LinkedList<>());return cnt;}public void Sum(TreeNode root, int sum, LinkedList<Integer> res) {//dfsif (root == null) return;res.add(root.val);cnt += um(res);Sum(root.left, sum + root.val, res);Sum(root.right, sum + root.val, res);res.removeLast();}public int um(LinkedList<Integer> res) {//找當前數組符合的連續子數組int temp = 0, r = 0;for (int i = res.size() - 1; i >= 0; i--) {r += res.get(i);if (r == tar) temp++;}return temp;} }遞歸+前綴和+回溯代碼
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {int tar;public int pathSum(TreeNode root, int sum) {tar = sum;HashMap<Integer,Integer> map=new HashMap<>();map.put(0,1);//節點本身也算路徑return helper(root, 0,map);}public int helper(TreeNode root, int sum, HashMap<Integer,Integer> map) {if (root == null) return 0;int cnt=0;int res=sum+root.val;cnt +=map.getOrDefault(res-tar,0);//符合的前綴和出現的次數就是路徑的數量map.put(res,map.getOrDefault(res,0)+1);if(root.left!=null) cnt+=helper(root.left, res, map);if(root.right!=null) cnt+=helper(root.right, res, map);map.put(res,map.get(res)-1);//回溯return cnt;} }總結
以上是生活随笔為你收集整理的leetcode面试题 04.12. 求和路径(dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么做梦会梦到不认识的人
- 下一篇: 梦到裤子弄脏是什么意思