Skip to content

Commit 7dbbefa

Browse files
committed
feat: add solutions to lcof problem: No.34
1 parent dc75b49 commit 7dbbefa

File tree

7 files changed

+267
-237
lines changed

7 files changed

+267
-237
lines changed

lcof/面试题34. 二叉树中和为某一值的路径/README.md

Lines changed: 143 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,11 @@
5151

5252
<!-- 这里可写通用的实现逻辑 -->
5353

54-
先序遍历+路径记录。
54+
**方法一:递归**
55+
56+
从根节点开始,递归遍历每个节点,每次递归时,将当前节点值加入到路径中,然后判断当前节点是否为叶子节点,如果是叶子节点并且路径和等于目标值,则将该路径加入到结果中。如果当前节点不是叶子节点,则递归遍历其左右子节点。递归遍历时,需要将当前节点从路径中移除,以确保返回父节点时路径刚好是从根节点到父节点。
57+
58+
时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。
5559

5660
<!-- tabs:start -->
5761

@@ -62,30 +66,27 @@
6266
```python
6367
# Definition for a binary tree node.
6468
# class TreeNode:
65-
# def __init__(self, x):
66-
# self.val = x
67-
# self.left = None
68-
# self.right = None
69-
70-
69+
# def __init__(self, val=0, left=None, right=None):
70+
# self.val = val
71+
# self.left = left
72+
# self.right = right
7173
class Solution:
72-
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
73-
def dfs(root, sum):
74+
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
75+
def dfs(root, s):
7476
if root is None:
7577
return
76-
path.append(root.val)
77-
if root.val == sum and root.left is None and root.right is None:
78-
res.append(path.copy())
79-
dfs(root.left, sum - root.val)
80-
dfs(root.right, sum - root.val)
81-
path.pop()
82-
83-
if not root:
84-
return []
85-
res = []
86-
path = []
87-
dfs(root, sum)
88-
return res
78+
t.append(root.val)
79+
s -= root.val
80+
if root.left is None and root.right is None and s == 0:
81+
ans.append(t[:])
82+
dfs(root.left, s)
83+
dfs(root.right, s)
84+
t.pop()
85+
86+
ans = []
87+
t = []
88+
dfs(root, target)
89+
return ans
8990
```
9091

9192
### **Java**
@@ -99,126 +100,146 @@ class Solution:
99100
* int val;
100101
* TreeNode left;
101102
* TreeNode right;
102-
* TreeNode(int x) { val = x; }
103+
* TreeNode() {}
104+
* TreeNode(int val) { this.val = val; }
105+
* TreeNode(int val, TreeNode left, TreeNode right) {
106+
* this.val = val;
107+
* this.left = left;
108+
* this.right = right;
109+
* }
103110
* }
104111
*/
105112
class Solution {
106-
private List<List<Integer>> res;
107-
private List<Integer> path;
108-
109-
public List<List<Integer>> pathSum(TreeNode root, int sum) {
110-
if (root == null) return Collections.emptyList();
111-
res = new ArrayList<>();
112-
path = new ArrayList<>();
113-
dfs(root, sum);
114-
return res;
113+
private List<Integer> t = new ArrayList<>();
114+
private List<List<Integer>> ans = new ArrayList<>();
115+
116+
public List<List<Integer>> pathSum(TreeNode root, int target) {
117+
dfs(root, target);
118+
return ans;
115119
}
116120

117-
private void dfs(TreeNode root, int sum) {
121+
private void dfs(TreeNode root, int s) {
118122
if (root == null) {
119123
return;
120124
}
121-
path.add(root.val);
122-
if (root.val == sum && root.left == null && root.right == null) {
123-
res.add(new ArrayList<>(path));
125+
t.add(root.val);
126+
s -= root.val;
127+
if (root.left == null && root.right == null && s == 0) {
128+
ans.add(new ArrayList<>(t));
124129
}
125-
dfs(root.left, sum - root.val);
126-
dfs(root.right, sum - root.val);
127-
path.remove(path.size() - 1);
130+
dfs(root.left, s);
131+
dfs(root.right, s);
132+
t.remove(t.size() - 1);
128133
}
129134
}
130135
```
131136

132-
### **JavaScript**
137+
### **C++**
133138

134-
```js
139+
```cpp
135140
/**
136141
* Definition for a binary tree node.
137-
* function TreeNode(val) {
138-
* this.val = val;
139-
* this.left = this.right = null;
140-
* }
141-
*/
142-
/**
143-
* @param {TreeNode} root
144-
* @param {number} sum
145-
* @return {number[][]}
142+
* struct TreeNode {
143+
* int val;
144+
* TreeNode *left;
145+
* TreeNode *right;
146+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
147+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
148+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
149+
* };
146150
*/
147-
var pathSum = function (root, sum) {
148-
if (!root) return [];
149-
let res = [];
150-
function dfs(node, sum, arr) {
151-
if (!node) return;
152-
arr = [...arr, node.val];
153-
if (node.val === sum && !node.left && !node.right) {
154-
res.push(arr);
155-
return;
156-
}
157-
dfs(node.left, sum - node.val, arr);
158-
dfs(node.right, sum - node.val, arr);
151+
class Solution {
152+
public:
153+
vector<vector<int>> pathSum(TreeNode* root, int target) {
154+
vector<vector<int>> ans;
155+
vector<int> t;
156+
function<void(TreeNode* root, int s)> dfs = [&](TreeNode* root, int s) {
157+
if (!root) {
158+
return;
159+
}
160+
t.push_back(root->val);
161+
s -= root->val;
162+
if (!root->left && !root->right && !s) {
163+
ans.push_back(t);
164+
}
165+
dfs(root->left, s);
166+
dfs(root->right, s);
167+
t.pop_back();
168+
};
169+
dfs(root, target);
170+
return ans;
159171
}
160-
dfs(root, sum, []);
161-
return res;
162172
};
163173
```
164174
165175
### **Go**
166176
167177
```go
168-
var res [][]int
169-
func pathSum(root *TreeNode, sum int) [][]int {
170-
res = [][]int{}
171-
if root == nil {
172-
return res
173-
}
174-
helper(root, sum, []int{})
175-
return res
176-
}
177-
178-
func helper(node *TreeNode, target int, ans []int) {
179-
if node == nil {
180-
return
181-
}
182-
ans = append(ans,node.Val)
183-
target -= node.Val
184-
if target == 0 && node.Left == nil && node.Right == nil {
185-
tmp := make([]int,len(ans))
186-
copy(tmp,ans)
187-
res = append(res,tmp)
188-
} else {
189-
helper(node.Left, target, ans)
190-
helper(node.Right, target, ans)
191-
}
178+
/**
179+
* Definition for a binary tree node.
180+
* type TreeNode struct {
181+
* Val int
182+
* Left *TreeNode
183+
* Right *TreeNode
184+
* }
185+
*/
186+
func pathSum(root *TreeNode, target int) (ans [][]int) {
187+
t := []int{}
188+
var dfs func(*TreeNode, int)
189+
dfs = func(root *TreeNode, s int) {
190+
if root == nil {
191+
return
192+
}
193+
t = append(t, root.Val)
194+
s -= root.Val
195+
if root.Left == nil && root.Right == nil && s == 0 {
196+
cp := make([]int, len(t))
197+
copy(cp, t)
198+
ans = append(ans, cp)
199+
}
200+
dfs(root.Left, s)
201+
dfs(root.Right, s)
202+
t = t[:len(t)-1]
203+
}
204+
dfs(root, target)
205+
return
192206
}
193207
```
194208

195-
### **C++**
196-
197-
```cpp
198-
class Solution {
199-
public:
200-
vector<vector<int>> pathSum(TreeNode* root, int target) {
201-
vector<vector<int>> ans;
202-
vector<int> path;
203-
dfs(root, ans, path, target);
204-
return ans;
205-
}
209+
### **JavaScript**
206210

207-
void dfs(TreeNode* root, vector<vector<int>>& ans, vector<int>& path, int target) {
208-
if (root == NULL) {
211+
```js
212+
/**
213+
* Definition for a binary tree node.
214+
* function TreeNode(val, left, right) {
215+
* this.val = (val===undefined ? 0 : val)
216+
* this.left = (left===undefined ? null : left)
217+
* this.right = (right===undefined ? null : right)
218+
* }
219+
*/
220+
/**
221+
* @param {TreeNode} root
222+
* @param {number} target
223+
* @return {number[][]}
224+
*/
225+
var pathSum = function (root, target) {
226+
const ans = [];
227+
const t = [];
228+
const dfs = (root, s) => {
229+
if (!root) {
209230
return;
210231
}
211-
target -= root->val;
212-
path.push_back(root->val);
213-
if (root->left == NULL && root->right == NULL) {
214-
if (target == 0) {
215-
ans.push_back(vector<int>(path));
216-
}
232+
t.push(root.val);
233+
s -= root.val;
234+
if (!root.left && !root.right && !s) {
235+
ans.push([...t]);
217236
}
218-
dfs(root->left, ans, path, target);
219-
dfs(root->right, ans, path, target);
220-
path.pop_back();
221-
}
237+
dfs(root.left, s);
238+
dfs(root.right, s);
239+
t.pop();
240+
};
241+
dfs(root, target);
242+
return ans;
222243
};
223244
```
224245

@@ -393,30 +414,26 @@ impl Solution {
393414
* }
394415
*/
395416
public class Solution {
396-
List<IList<int>> res;
397-
List<int> path;
417+
private List<IList<int>> ans = new List<IList<int>>();
418+
private List<int> t = new List<int>();
398419

399420
public IList<IList<int>> PathSum(TreeNode root, int target) {
400-
res = new List<IList<int>>();
401-
path = new List<int>();
402-
if (root == null) {
403-
return res;
404-
}
405421
dfs(root, target);
406-
return res;
422+
return ans;
407423
}
408424

409-
public void dfs(TreeNode root, int target) {
425+
private void dfs(TreeNode root, int s) {
410426
if (root == null) {
411427
return;
412428
}
413-
path.Add(root.val);
414-
if (root.val == target && root.left is null && root.right is null) {
415-
res.Add(new List<int>(path));
429+
t.Add(root.val);
430+
s -= root.val;
431+
if (root.left == null && root.right == null && s == 0) {
432+
ans.Add(new List<int>(t));
416433
}
417-
dfs(root.left, target - root.val);
418-
dfs(root.right, target - root.val);
419-
path.RemoveAt(path.Count - 1);
434+
dfs(root.left, s);
435+
dfs(root.right, s);
436+
t.RemoveAt(t.Count - 1);
420437
}
421438
}
422439
```
Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
112
class Solution {
213
public:
314
vector<vector<int>> pathSum(TreeNode* root, int target) {
415
vector<vector<int>> ans;
5-
vector<int> path;
6-
dfs(root, ans, path, target);
7-
return ans;
8-
}
9-
10-
void dfs(TreeNode* root, vector<vector<int>>& ans, vector<int>& path, int target) {
11-
if (root == NULL) {
12-
return;
13-
}
14-
target -= root->val;
15-
path.push_back(root->val);
16-
if (root->left == NULL && root->right == NULL) {
17-
if (target == 0) {
18-
ans.push_back(vector<int>(path));
16+
vector<int> t;
17+
function<void(TreeNode* root, int s)> dfs = [&](TreeNode* root, int s) {
18+
if (!root) {
19+
return;
1920
}
20-
}
21-
dfs(root->left, ans, path, target);
22-
dfs(root->right, ans, path, target);
23-
path.pop_back();
21+
t.push_back(root->val);
22+
s -= root->val;
23+
if (!root->left && !root->right && !s) {
24+
ans.push_back(t);
25+
}
26+
dfs(root->left, s);
27+
dfs(root->right, s);
28+
t.pop_back();
29+
};
30+
dfs(root, target);
31+
return ans;
2432
}
25-
};
33+
};

0 commit comments

Comments
 (0)