import java.util.*;

/*

  • public class TreeNode {
  • int val = 0;
  • TreeNode left = null;
  • TreeNode right = null;
  • } / //因为不需要打印具体路径,所以只需要判断和是否存在就可以 //采用深度优先遍历和回溯 public class Solution { /* *
    • @param root TreeNode类
    • @param sum int整型
    • @return bool布尔型 */ public boolean hasPathSum (TreeNode root, int sum) { return dfs(root,sum); } private boolean dfs(TreeNode root,int sum){ if(root == null){ return false; } sum = sum - root.val; if(sum == 0 && root.left == null && root.right == null){ return true; } return dfs(root.left,sum) || dfs(root.right,sum); }

}