Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 09293fe

Browse files
committed
优化 0257.二叉树的所有路径.md Python3解法
1. 优化Python3递归解法 2. 追加Python3迭代解法 3. 尽量遵守PEP8,增强可读性
1 parent ab1dddb commit 09293fe

File tree

1 file changed

+47
-15
lines changed

1 file changed

+47
-15
lines changed

‎problems/0257.二叉树的所有路径.md

Lines changed: 47 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -371,25 +371,57 @@ class Solution {
371371
Python:
372372
```Python
373373
class Solution:
374+
"""二叉树的所有路径 递归法"""
375+
374376
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
390398

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
391422
```
392423

424+
393425
Go:
394426
```go
395427
func binaryTreePaths(root *TreeNode) []string {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /