Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e8fd03b

Browse files
authoredJan 3, 2019
Add files via upload
1 parent a661b5c commit e8fd03b

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
 

‎Path Sum/Path_Sum.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// 第一种思路 使用递归
2+
// 8ms 57.10%
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
14+
class Solution {
15+
public:
16+
bool hasPathSum(TreeNode* root, int sum) {
17+
18+
// 如果是空树,则直接返回
19+
if (root == 0)
20+
return false;
21+
22+
// 如果查询到了叶子节点
23+
if (root->left == 0 && root->right == 0)
24+
{
25+
if (sum == root->val)
26+
return true;
27+
else
28+
return false;
29+
}
30+
31+
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
32+
}
33+
};

‎Path Sum/Path_Sum.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# 第一种思路 使用递归
2+
# 76ms 39.18%
3+
4+
# Definition for a binary tree node.
5+
# class TreeNode:
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.left = None
9+
# self.right = None
10+
11+
class Solution:
12+
def hasPathSum(self, root, sum):
13+
"""
14+
:type root: TreeNode
15+
:type sum: int
16+
:rtype: bool
17+
"""
18+
# 如果是空树,则直接返回
19+
if root is None:
20+
return False
21+
22+
# 如果查询到了叶子节点
23+
if root.left is None and root.right is None:
24+
if sum == root.val:
25+
return True
26+
else:
27+
return False
28+
29+
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
30+

0 commit comments

Comments
 (0)
Please sign in to comment.