X.<tag-数组和二分查找>-lt.xx-xxxxxx + lt.xx-xxxxxx
lt.112. 路径总和
[案例需求]
[思路分析一, 递归]
[代码实现]
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null)return false;
return dfs(root, targetSum - root.val);
}
public boolean dfs(TreeNode root, int count){
if(root.left == null && root.right == null && count == 0)return true;
if(root.left == null && root.right == null )return false;
if(root.left != null){
count -= root.left.val;
if(dfs(root.left, count))return true;
count += root.left.val;
}
if(root.right != null){
count -= root.right.val;
if(dfs(root.right, count))return true;
count += root.right.val;
}
return false;
}
}
[思路分析二, 迭代法]
[代码实现]
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
Queue<TreeNode> nodes = new LinkedList<>();
Queue<Integer> nodesVal = new LinkedList<>();
if(root == null)return false;
nodes.add(root);
nodesVal.add(root.val);
while(!nodes.isEmpty()){
root = nodes.poll();
int temp = nodesVal.poll();
if(root.left == null && root.right == null){
if(temp == targetSum)return true;
continue;
}
if(root.left != null){
nodes.add(root.left);
nodesVal.add(root.left.val + temp);
}
if(root.right != null){
nodes.add(root.right);
nodesVal.add(root.right.val + temp);
}
}
return false;
}
}
|