26_112. 路径总和


题目描述:

解题思路:

  • 递归:从当前节点root到叶子节点满足其路径和是sum,就可以转化为子问题,从当前节点的子节点,到叶子节点其路径和是sum - root.val
  • 广度优先搜索:可以使用两个队列,一个队列用于广度优先搜索的辅助队列,一个队列记录与辅助队列相同步的从根节点到该节点的路径总和。两个队列操作同步,就能保证在找到符合条件的路径时,直接返回。
递归
//递归:
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        
        if (root.left == null && root.right == null ) {
            if (root.val == targetSum) {
                return true;
            }else {
                return false;
            }
        }
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
        
        
    }

}
广度优先搜索
//广度优先搜索:
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        int sum = root.val;
        if (root.left == null && root.right == null ) {
            if (sum == targetSum) {
                return true;
            }
        }
        
        
    }
    public int dfs (TreeNode root) {
        
    }
}