Skip to content

Commit 1a4a287

Browse files
authored
增加112.路径总和 JAVA 迭代版本
1 parent ff2ec86 commit 1a4a287

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

problems/0112.路径总和.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,36 @@ class Solution {
345345
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
346346
}
347347
}
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+
348378
```
349379

350380
0113.路径总和-ii

0 commit comments

Comments
 (0)