@@ -371,25 +371,57 @@ class Solution {
371
371
Python:
372
372
``` Python
373
373
class Solution :
374
+ """ 二叉树的所有路径 递归法"""
375
+
374
376
def binaryTreePaths (self , root : TreeNode) -> List[str ]:
375
- path= []
376
- res= []
377
- def backtrace (root , path ):
378
- if not root:return
379
- path.append(root.val)
380
- if (not root.left)and (not root.right):
381
- res.append(path[:])
382
- ways= []
383
- if root.left:ways.append(root.left)
384
- if root.right:ways.append(root.right)
385
- for way in ways:
386
- backtrace(way,path)
387
- path.pop()
388
- backtrace(root,path)
389
- return [" ->" .join(list (map (str ,i))) for i in res]
377
+ path, result = ' ' , []
378
+ self .traversal(root, path, result)
379
+ return result
380
+
381
+ def traversal (self , cur : TreeNode, path : List, result : List):
382
+ path += str (cur.val)
383
+ # 如果当前节点为叶子节点,添加路径到结果中
384
+ if not (cur.left or cur.right):
385
+ result.append(path)
386
+ return
387
+
388
+ if cur.left:
389
+ self .traversal(cur.left, path + ' ->' , result)
390
+
391
+ if cur.right:
392
+ self .traversal(cur.right, path + ' ->' , result)
393
+
394
+ ```
395
+
396
+ ``` python
397
+ from collections import deque
390
398
399
+
400
+ class Solution :
401
+ """ 二叉树的所有路径 迭代法"""
402
+
403
+ def binaryTreePaths (self , root : TreeNode) -> List[str ]:
404
+ # 题目中节点数至少为1
405
+ stack, path_st, result = deque([root]), deque(), []
406
+ path_st.append(str (root.val))
407
+
408
+ while stack:
409
+ cur = stack.pop()
410
+ path = path_st.pop()
411
+ # 如果当前节点为叶子节点,添加路径到结果中
412
+ if not (cur.left or cur.right):
413
+ result.append(path)
414
+ if cur.right:
415
+ stack.append(cur.right)
416
+ path_st.append(path + ' ->' + str (cur.right.val))
417
+ if cur.left:
418
+ stack.append(cur.left)
419
+ path_st.append(path + ' ->' + str (cur.left.val))
420
+
421
+ return result
391
422
```
392
423
424
+
393
425
Go:
394
426
``` go
395
427
func binaryTreePaths (root *TreeNode ) []string {
0 commit comments