bobo老师,我用DFS解了这道题。但是dfs没有返回值,同时维护了一个成员变量findSum(代码如下)。我在想如何改造dfs函数, 使其直接返回true or false,但是失败了。能否请老师看下,如何把dfs改成boolean返回值类型呢?这样直接return dfs就行了
class Solution { private boolean findSum = false; public boolean hasPathSum(TreeNode root, int targetSum) { if (root == null) return false; dfs(root, root.val, targetSum); return findSum; } private void dfs(TreeNode node, int sum, int targetSum) { if (node.left == null && node.right == null) { if (sum == targetSum) { findSum = true; return; } } else { if (node.left != null) dfs(node.left, sum + node.left.val, targetSum); if (node.right != null) dfs(node.right, sum + node.right.val, targetSum); } } }