1+ // 112. 路径总和
2+
3+
4+ /**
5+ * Definition for a binary tree node.
6+ * public class TreeNode {
7+ * int val;
8+ * TreeNode left;
9+ * TreeNode right;
10+ * TreeNode() {}
11+ * TreeNode(int val) { this.val = val; }
12+ * TreeNode(int val, TreeNode left, TreeNode right) {
13+ * this.val = val;
14+ * this.left = left;
15+ * this.right = right;
16+ * }
17+ * }
18+ */
19+
20+
21+ /*
22+ 递归:
23+ 1、方法功能:入参是一个节点,返回该节点值是否等于目标和
24+ 2、终止条件:节点为空时返回false
25+ 3、返回结果:节点不为空时,如果是叶子结点且节点值等于目标和,则返回true
26+ 4、递归逻辑:
27+ 1)没到达叶子结点前,左右节点同样要计算获取结果,再拿结果处理,其中一个为true则返回true
28+ 2)自顶向下累减传递目标和,到叶子结点后,自底向上返回处理结果
29+ */
30+ class Solution {
31+ public boolean hasPathSum (TreeNode root , int targetSum ) {
32+ if (root == null ) {
33+ return false ;
34+ }
35+ if (root .left == null && root .right == null && root .val == targetSum ) {
36+ return true ;
37+ }
38+ targetSum -= root .val ;
39+ return hasPathSum (root .left , targetSum ) || hasPathSum (root .right , targetSum );
40+ }
41+ }
42+
43+
44+ /*
45+ 广度优先搜索:层序遍历节点,利用两个队列分别保存 节点 和 到达节点时的路径和,当节点是叶子节点时,判断路径和等于目标和则返回true,遍历结束后没有找到目标和则返回false
46+ */
47+ class Solution {
48+ public boolean hasPathSum (TreeNode root , int targetSum ) {
49+ if (root == null ) {
50+ return false ;
51+ }
52+ Queue <TreeNode > nodeQueue = new LinkedList <>();
53+ Queue <Integer > sumQueue = new LinkedList <>();
54+ nodeQueue .add (root );
55+ sumQueue .add (root .val );
56+ while (!nodeQueue .isEmpty ()) {
57+ TreeNode node = nodeQueue .poll ();
58+ Integer sum = sumQueue .poll ();
59+ if (node .left == null && node .right == null && sum == targetSum ) {
60+ return true ;
61+ }
62+ if (node .left != null ) {
63+ nodeQueue .add (node .left );
64+ sumQueue .add (sum + node .left .val );
65+ }
66+ if (node .right != null ) {
67+ nodeQueue .add (node .right );
68+ sumQueue .add (sum + node .right .val );
69+ }
70+ }
71+ return false ;
72+ }
73+ }
0 commit comments