File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -345,6 +345,36 @@ class Solution {
345
345
return hasPathSum(root. left, targetSum - root. val) || hasPathSum(root. right, targetSum - root. val);
346
346
}
347
347
}
348
+ ```
349
+ 迭代
350
+ ``` java
351
+ class Solution {
352
+ public boolean hasPathSum (TreeNode root , int targetSum ) {
353
+ if (root== null )return false ;
354
+ Stack<TreeNode > stack1 = new Stack<> ();
355
+ Stack<Integer > stack2 = new Stack<> ();
356
+ stack1. push(root);stack2. push(root. val);
357
+ while (! stack1. isEmpty()){
358
+ int size = stack1. size();
359
+ for (int i= 0 ;i< size;i++ ){
360
+ TreeNode node = stack1. pop();int sum= stack2. pop();
361
+ // 如果该节点是叶子节点了,同时该节点的路径数值等于sum,那么就返回true
362
+ if (node. left== null && node. right== null && sum== targetSum)return true ;
363
+ // 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
364
+ if (node. right!= null ){
365
+ stack1. push(node. right);stack2. push(sum+ node. right. val);
366
+ }
367
+ // 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
368
+ if (node. left!= null ){
369
+ stack1. push(node. left);stack2. push(sum+ node. left. val);
370
+ }
371
+ }
372
+ }
373
+ return false ;
374
+ }
375
+
376
+ }
377
+
348
378
```
349
379
350
380
0113.路径总和-ii
You can’t perform that action at this time.
0 commit comments