Path Sum I 路径总和 I
代码部分一(0ms):
class Solution {
boolean res = false;
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
int count = 0;
isHasPathSum(root, sum, count);
return res;
}
public void isHasPathSum(TreeNode root, int sum, int count){
count += root.val;
if(root.left == null && root.right == null){
if(count == sum){
res = true;
return;
}
count = 0;
}
if(root.left != null){
isHasPathSum(root.left, sum, count);
}
if(root.right != null){
isHasPathSum(root.right, sum, count);
}
}
}
-
若树为空,返回false
-
调用isHasPathSum()
-
将当前节点的值 root.val 增到 count ,判断当前节点是否叶子节点,此路径总值 count 是否等于 sum,是则return true
-
否则 count 置 0,进行下一路径遍历。
-
返回 res
代码部分二(0ms):
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if (root.left == null && root.right == null) return sum == root.val;
if (root.left == null) return hasPathSum(root.right, sum-root.val);
if (root.right == null) return hasPathSum(root.left, sum-root.val);
return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
}
}
-
若树为空 ,返回个false
-
若当前节点为叶子节点,将其赋值为 sum,并返回该值
-
对左右子节点进行遍历
-
若左右路径遍历中有存在路径总值为 sum ,返回true
-
将目标值sum,逐个数值递减,当遍历到子叶节点时,sum 应 == root.val
Path Sum III 路径总和 III
代码部分一(27ms):
class Solution {
public int pathSum(TreeNode root, int sum) {
if(root == null)
return 0;
return countSum(root, sum, 0) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
public int countSum(TreeNode node, int sum, int pre){
if(node == null)
return 0;
pre += node.val;
int res = 0;
if(pre == sum)
res = 1;
return res + countSum(node.left, sum, pre)+countSum(node.right, sum, pre);
}
}
-
若树为空,返回 0
-
调用countSum(),对左右子树进行递归
-
向pre中增加一条路径上的每个节点的值
-
若sum 等于 pre 时,返回1
-
递归countSum()
-
返回值
代码部分二(16ms):
class Solution {
int counter = 0;
public int pathSum(TreeNode root, int sum) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0,1);
dfs(root, 0, sum, map);
return counter;
}
private void dfs(TreeNode root, int sum, int target, HashMap<Integer, Integer> map){
if(root == null){
return;
}
sum += root.val;
if(map.containsKey(sum - target)){
counter+=map.get(sum - target);
}
if(map.containsKey(sum)){
map.put(sum, map.get(sum)+1);
}else{
map.put(sum,1);
}
dfs(root.left, sum, target, map);
dfs(root.right, sum, target, map);
map.put(sum, map.get(sum)-1);
}
}
-
创建 HashMap
-
进行dfs()深度遍历
-
若节点为空,返回
-
判断 map 中是否记录了 sum-target ,是则counter+1()
-
若map 中不存在 sum ,存入新纪录(sum,1),若存在,则记录加1
-
左右子树开始遍历
-
递归返回过程,将记录-1
- 在路径遍历过程,先不断将记录存入map, 并不断判断知道找到符合值。相同的值之所以要记录,因为当遍历至某节点,可能左右节点都可以令其满足