力扣 LeetCode 112. 路径总和(Day8:二叉树)
解题思路:
前中后序均可,实际上没有中的处理
targetSum递减操作
同样可以简化代码,只是不太直观的体现回溯逻辑
方法一:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null && targetSum == root.val)
return true;
if (root.left == null && root.right == null && targetSum != root.val)
return false;
if (root.left != null) {
targetSum -= root.val;
if (hasPathSum(root.left, targetSum) == true) return true;
targetSum += root.val;
}
if (root.right != null) {
targetSum -= root.val;
if (hasPathSum(root.right, targetSum) == true) return true;
targetSum += root.val;
}
return false;
}
}
方法二:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
targetSum -= root.val;
if (root.left == null && root.right == null)
return targetSum == 0;
if (root.left != null) {
if (hasPathSum(root.left, targetSum) == true) return true;
}
if (root.right != null) {
if (hasPathSum(root.right, targetSum) == true) return true;
}
return false;
}
}