Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2038 from Lozakaka/patch-2
Browse files Browse the repository at this point in the history
Update 0112.路径总和.md
  • Loading branch information
youngyangyang04 authored Apr 30, 2023
2 parents f979407 + 3f2a816 commit 45c3fd7
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions problems/0112.路径总和.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,42 @@ class solution {
}
}
```
```Java 統一迭代法
public boolean hasPathSum(TreeNode root, int targetSum) {
Stack<TreeNode> treeNodeStack = new Stack<>();
Stack<Integer> sumStack = new Stack<>();

if(root == null)
return false;
treeNodeStack.add(root);
sumStack.add(root.val);

while(!treeNodeStack.isEmpty()){
TreeNode curr = treeNodeStack.peek();
int tempsum = sumStack.pop();
if(curr != null){
treeNodeStack.pop();
treeNodeStack.add(curr);
treeNodeStack.add(null);
sumStack.add(tempsum);
if(curr.right != null){
treeNodeStack.add(curr.right);
sumStack.add(tempsum + curr.right.val);
}
if(curr.left != null){
treeNodeStack.add(curr.left);
sumStack.add(tempsum + curr.left.val);
}
}else{
treeNodeStack.pop();
TreeNode temp = treeNodeStack.pop();
if(temp.left == null && temp.right == null && tempsum == targetSum)
return true;
}
}
return false;
}
```

### 0113.路径总和-ii

Expand Down

0 comments on commit 45c3fd7

Please sign in to comment.