mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
@ -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
|
||||
|
||||
|
Reference in New Issue
Block a user