==========================努力奋斗财源广进==========================
给定一个二叉树root和一个值 sum ,判断是否有从根节点到叶子节点的节点值之和等于 sum 的路径。
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 dfs(TreeNode root, int target){
if(root == null) return false;
target -= root.val;
if(root.left == null && root.right == null && target == 0) return true;
return dfs(root.left, target) || dfs(root.right, target);
}
public boolean hasPathSum (TreeNode root, int sum) {
// write code here
if(root == null) return false;
return dfs(root, sum);
}
}
//待定
评论区记录复习记录
评论