bobo老师,我用DFS解了这道题。但是dfs没有返回值,同时维护了一个成员变量findSum(代码如下)。我在想如何改造dfs函数, 使其直接返回true or false,但是失败了。能否请老师看下,如何把dfs改成boolean返回值类型呢?这样直接return dfs就行了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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); } } } |