112. 路径总和
小于 1 分钟
112. 路径总和简单
解法思路:dfs
class Solution {
boolean res = false;
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null)
return false;
int sum = 0;
dfs(root, sum, targetSum);
return res;
}
public void dfs(TreeNode node, int sum, int target) {
sum += node.val;
if (node.left == null && node.right == null) {
if (sum == target)
res = true;
} else if (node.left == null) {
dfs(node.right, sum, target);
} else if (node.right == null) {
dfs(node.left, sum, target);
} else {
dfs(node.left, sum, target);
dfs(node.right, sum, target);
}
}
}
Powered by Waline v2.15.5