题目
思路
- 直接利用先序遍历,再每次遍历的时候减去当前节点的值,终止条件是到叶子节点时,它的值为0;
代码
路径总和public boolean hasPathSum(TreeNode root, int targetSum) {if (root != null && root.left == null&& root.right == null && targetSum == root.val) return true;if (root == null || root != null && root.left == null&& root.right == null && targetSum != root.val) return false;return hasPathSum(root.left, targetSum - root.val)|| hasPathSum(root.right, targetSum - root.val);}
