mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
@ -305,25 +305,34 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
private boolean flag = false;
|
|
||||||
public boolean hasPathSum(TreeNode root, int targetSum) {
|
public boolean hasPathSum(TreeNode root, int targetSum) {
|
||||||
has_2(root,targetSum);
|
if (root == null) {
|
||||||
return flag;
|
return false;
|
||||||
}
|
}
|
||||||
|
targetSum -= root.val;
|
||||||
public void has_2 (TreeNode root, int count) {
|
// 叶子结点
|
||||||
if (root == null) return;
|
if (root.left == null && root.right == null) {
|
||||||
if (root.left == null && root.right == null && count == root.val) {
|
return targetSum == 0;
|
||||||
flag = true;
|
|
||||||
}
|
}
|
||||||
if (root.left != null) has_2(root.left,count - root.val);
|
if (root.left != null) {
|
||||||
if (root.right != null) has_2(root.right,count - root.val);
|
boolean left = hasPathSum(root.left, targetSum);
|
||||||
|
if (left) {// 已经找到
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (root.right != null) {
|
||||||
|
boolean right = hasPathSum(root.right, targetSum);
|
||||||
|
if (right) {// 已经找到
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user