112. 路径总和
深度优先搜索
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
/**
* 递归终止条件
* 节点为空时返回false
* 节点没有孩子,剩余的数值等于节点值时返回true
*/
if (root == null){
return false;
}
if (root.left == null && root.right == null){
return targetSum == root.val;
}
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(logn)
*/