Skip to content

Commit 37fe058

Browse files
committedFeb 19, 2020
更新了113和113的说明
1 parent 7099114 commit 37fe058

File tree

3 files changed

+98
-0
lines changed

3 files changed

+98
-0
lines changed
 

‎README.md

+7
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,10 @@
22

33
此为我的Leetcode刷题记录
44

5+
## 分类整理
6+
7+
### 二叉树
8+
9+
#### 二叉树的遍历
10+
11+
+ No.113: [cpp](cpp/113.cpp) [python](python/113.py)

‎cpp/113.cpp

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <vector>
2+
#include <iostream>
3+
using std::vector;
4+
5+
struct TreeNode {
6+
int val;
7+
TreeNode *left;
8+
TreeNode *right;
9+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10+
};
11+
/**
12+
* Definition for a binary tree node.
13+
* struct TreeNode {
14+
* int val;
15+
* TreeNode *left;
16+
* TreeNode *right;
17+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
18+
* };
19+
*/
20+
21+
/* 16 ms 69.96%
22+
* 20 MB 50.00%
23+
*/
24+
class Solution {
25+
public:
26+
vector<vector<int>> res;
27+
int sum;
28+
vector<vector<int>> pathSum(TreeNode* root, int sum) {
29+
vector<int> stack;
30+
this->sum = sum;
31+
order(root, stack, 0);
32+
return res;
33+
}
34+
void order(TreeNode* root, vector<int>& stack,int sum) {
35+
if (root != nullptr) {
36+
stack.push_back(root->val);
37+
sum += root->val;
38+
if (root->left || root->right) { // 是否是根节点
39+
order(root->left, stack, sum);
40+
order(root->right, stack, sum);
41+
} else {
42+
if (sum == this->sum) {
43+
this->res.push_back(stack); // push_back为拷贝操作
44+
}
45+
}
46+
stack.pop_back();
47+
}
48+
}
49+
};

‎python/113.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution:
2+
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
3+
self.res = []
4+
self.target = sum
5+
self.order(root, [], 0)
6+
return self.res
7+
8+
def order(self, root, ls, sum):
9+
"""
10+
52 ms
11+
17.9 MB
12+
"""
13+
if root is not None:
14+
ls += [root.val]
15+
sum += root.val
16+
if root.left != None or root.right != None: # 叶子节点判断
17+
self.inorder(root.left, ls[:], sum) # ls[:]很浪费空间和时间, 因此order2的时候改成复用ls,加一个pop操作即可
18+
self.inorder(root.right, ls[:], sum)
19+
else:
20+
if sum == self.target:
21+
# 这里会重复append
22+
self.res.append(ls)
23+
24+
def order(self, root, ls, sum):
25+
"""
26+
44 ms 72.95%
27+
13.8 MB 100%
28+
"""
29+
if root is not None:
30+
ls += [root.val]
31+
sum += root.val
32+
if root.left != None or root.right != None:
33+
self.inorder(root.left, ls, sum) # 此处做了修改
34+
self.inorder(root.right, ls, sum)
35+
else:
36+
if sum == self.target:
37+
# 这里会重复append
38+
self.res.append(ls[:]) # 这里还是copy操作,因为ls是引用
39+
ls.pop() # 弹出栈
40+
41+
42+

0 commit comments

Comments
 (0)
Please sign in to comment.