38
38
39
39
<!-- 这里可写通用的实现逻辑 -->
40
40
41
- 深度优先搜索+路径记录。
41
+ ** 方法一:DFS**
42
+
43
+ 我们可以使用深度优先搜索的方法遍历整棵二叉树,每一次我们将当前的节点添加到路径中。如果当前的节点是叶子节点,则我们将整个路径加入到答案中。否则我们继续递归遍历节点的孩子节点。最后当我们递归结束返回到当前节点时,我们需要将当前节点从路径中删除。
44
+
45
+ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。
42
46
43
47
<!-- tabs:start -->
44
48
54
58
# self.left = left
55
59
# self.right = right
56
60
class Solution :
57
- def binaryTreePaths (self , root : TreeNode) -> List[str ]:
58
- def dfs (root ):
61
+ def binaryTreePaths (self , root : Optional[ TreeNode] ) -> List[str ]:
62
+ def dfs (root : Optional[TreeNode] ):
59
63
if root is None :
60
64
return
61
65
t.append(str (root.val))
62
66
if root.left is None and root.right is None :
63
- ans.append(' ->' .join(t))
64
- dfs(root.left)
65
- dfs(root.right)
67
+ ans.append(" ->" .join(t))
68
+ else :
69
+ dfs(root.left)
70
+ dfs(root.right)
66
71
t.pop()
67
72
68
- t = []
69
73
ans = []
74
+ t = []
70
75
dfs(root)
71
76
return ans
72
77
```
@@ -92,12 +97,10 @@ class Solution:
92
97
* }
93
98
*/
94
99
class Solution {
95
- private List<String > ans;
96
- private List<String > t;
100
+ private List<String > ans = new ArrayList<> () ;
101
+ private List<String > t = new ArrayList<> () ;
97
102
98
103
public List<String > binaryTreePaths (TreeNode root ) {
99
- ans = new ArrayList<> ();
100
- t = new ArrayList<> ();
101
104
dfs(root);
102
105
return ans;
103
106
}
@@ -109,45 +112,62 @@ class Solution {
109
112
t. add(root. val + " " );
110
113
if (root. left == null && root. right == null ) {
111
114
ans. add(String . join(" ->" , t));
115
+ } else {
116
+ dfs(root. left);
117
+ dfs(root. right);
112
118
}
113
- dfs(root. left);
114
- dfs(root. right);
115
119
t. remove(t. size() - 1 );
116
120
}
117
121
}
118
122
```
119
123
120
- ### ** TypeScript **
124
+ ### ** C++ **
121
125
122
- ``` ts
126
+ ``` cpp
123
127
/* *
124
128
* Definition for a binary tree node.
125
- * class TreeNode {
126
- * val: number
127
- * left: TreeNode | null
128
- * right: TreeNode | null
129
- * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
130
- * this.val = (val===undefined ? 0 : val)
131
- * this.left = (left===undefined ? null : left)
132
- * this.right = (right===undefined ? null : right)
133
- * }
134
- * }
129
+ * struct TreeNode {
130
+ * int val;
131
+ * TreeNode *left;
132
+ * TreeNode *right;
133
+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
134
+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
135
+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
136
+ * };
135
137
*/
138
+ class Solution {
139
+ public:
140
+ vector<string > binaryTreePaths(TreeNode* root) {
141
+ vector<string > ans;
142
+ vector<string > t;
143
+ function<void(TreeNode* )> dfs = [ &] (TreeNode* root) {
144
+ if (!root) {
145
+ return;
146
+ }
147
+ t.push_back(to_string(root->val));
148
+ if (!root->left && !root->right) {
149
+ ans.push_back(join(t));
150
+ } else {
151
+ dfs(root->left);
152
+ dfs(root->right);
153
+ }
154
+ t.pop_back();
155
+ };
156
+ dfs(root);
157
+ return ans;
158
+ }
136
159
137
- function binaryTreePaths(root : TreeNode | null ): string [] {
138
- let ans = [];
139
- let t = [];
140
- function dfs(root ) {
141
- if (! root ) return ;
142
- t .push (String (root .val ));
143
- if (! root .left && ! root .right ) ans .push (t .join (' ->' ));
144
- dfs (root .left );
145
- dfs (root .right );
146
- t .pop ();
160
+ string join(vector<string>& t, string sep = "->") {
161
+ string ans;
162
+ for (int i = 0; i < t.size(); ++i) {
163
+ if (i > 0) {
164
+ ans += sep;
165
+ }
166
+ ans += t[i];
167
+ }
168
+ return ans;
147
169
}
148
- dfs (root );
149
- return ans ;
150
- }
170
+ };
151
171
```
152
172
153
173
### ** Go**
@@ -161,61 +181,63 @@ function binaryTreePaths(root: TreeNode | null): string[] {
161
181
* Right *TreeNode
162
182
* }
163
183
*/
164
- func binaryTreePaths (root *TreeNode ) []string {
165
- var ans []string
166
- var t []string
167
- var dfs func (root *TreeNode)
184
+ func binaryTreePaths (root *TreeNode ) (ans []string ) {
185
+ t := []string {}
186
+ var dfs func (*TreeNode)
168
187
dfs = func (root *TreeNode) {
169
188
if root == nil {
170
189
return
171
190
}
172
191
t = append (t, strconv.Itoa (root.Val ))
173
192
if root.Left == nil && root.Right == nil {
174
193
ans = append (ans, strings.Join (t, " ->" ))
194
+ } else {
195
+ dfs (root.Left )
196
+ dfs (root.Right )
175
197
}
176
- dfs (root.Left )
177
- dfs (root.Right )
178
198
t = t[:len (t)-1 ]
179
199
}
180
200
dfs (root)
181
- return ans
201
+ return
182
202
}
183
203
```
184
204
185
- ### ** C++ **
205
+ ### ** TypeScript **
186
206
187
- ``` cpp
207
+ ``` ts
188
208
/**
189
209
* Definition for a binary tree node.
190
- * struct TreeNode {
191
- * int val;
192
- * TreeNode *left;
193
- * TreeNode *right;
194
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
195
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
196
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
197
- * };
210
+ * class TreeNode {
211
+ * val: number
212
+ * left: TreeNode | null
213
+ * right: TreeNode | null
214
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
215
+ * this.val = (val===undefined ? 0 : val)
216
+ * this.left = (left===undefined ? null : left)
217
+ * this.right = (right===undefined ? null : right)
218
+ * }
219
+ * }
198
220
*/
199
- class Solution {
200
- public:
201
- vector<string > ans;
202
221
203
- vector<string> binaryTreePaths(TreeNode* root) {
204
- dfs(root, "");
205
- return ans;
206
- }
207
-
208
- void dfs (TreeNode* root, string t) {
209
- t += to_string(root->val);
210
- if (!root->left && !root->right) {
211
- ans.push_back(t);
222
+ function binaryTreePaths(root : TreeNode | null ): string [] {
223
+ const ans: string [] = [];
224
+ const t: number [] = [];
225
+ const dfs = (root : TreeNode | null ) => {
226
+ if (! root ) {
212
227
return ;
213
228
}
214
- t += "->";
215
- if (root->left) dfs(root->left, t);
216
- if (root->right) dfs(root->right, t);
217
- }
218
- };
229
+ t .push (root .val );
230
+ if (! root .left && ! root .right ) {
231
+ ans .push (t .join (' ->' ));
232
+ } else {
233
+ dfs (root .left );
234
+ dfs (root .right );
235
+ }
236
+ t .pop ();
237
+ };
238
+ dfs (root );
239
+ return ans ;
240
+ }
219
241
```
220
242
221
243
### ** ...**
0 commit comments