给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum 的 路径 的数目。
路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
在这里插入图片描述
方法一:树的遍历 + DFS
方法一:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int res = 0; public int pathSum(TreeNode root, int targetSum) { dfsTree(root, targetSum); return res; } // 递归所有根结点 public void dfsTree(TreeNode root, int targetSum) { if (root == null) return; dfsRoad(root, targetSum, root.val); dfsTree(root.left, targetSum); dfsTree(root.right, targetSum); } // 递归所有路径 public void dfsRoad(TreeNode root, int targetSum, int val) { if (val == targetSum) { res ++; } if (root.left != null) dfsRoad(root.left, targetSum, root.left.val + val); if (root.right != null) dfsRoad(root.right, targetSum, root.right.val + val); } }
方法二:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { //key记录路径,value记录该路径的个数 Map<Integer, Integer> map = new HashMap<>(); int res = 0; public int pathSum(TreeNode root, int targetSum) { map.put(0, 1); dfs(root, targetSum, 0); return res; } public void dfs(TreeNode root, int targetSum, int sum) { if (root == null) { return; } sum += root.val; //获取路径的个数 int cnt = map.getOrDefault(sum - targetSum, 0); res += cnt; //更新哈希表 该路径和对应的条数加一 map.put(sum, map.getOrDefault(sum, 0) + 1); //左右子树递归 dfs(root.left, targetSum, sum); dfs(root.right, targetSum, sum); //回溯恢复现场 使对应的路径数量减少一条即可 map.put(sum, map.getOrDefault(sum, 0) - 1); } }