mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
优化 0257.二叉树的所有路径.md Python3解法
1. 优化Python3递归解法 2. 追加Python3迭代解法 3. 尽量遵守PEP8,增强可读性
This commit is contained in:
@ -371,25 +371,57 @@ class Solution {
|
|||||||
Python:
|
Python:
|
||||||
```Python
|
```Python
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""二叉树的所有路径 递归法"""
|
||||||
|
|
||||||
def binaryTreePaths(self, root: TreeNode) -> List[str]:
|
def binaryTreePaths(self, root: TreeNode) -> List[str]:
|
||||||
path=[]
|
path, result = '', []
|
||||||
res=[]
|
self.traversal(root, path, result)
|
||||||
def backtrace(root, path):
|
return result
|
||||||
if not root:return
|
|
||||||
path.append(root.val)
|
def traversal(self, cur: TreeNode, path: List, result: List):
|
||||||
if (not root.left)and (not root.right):
|
path += str(cur.val)
|
||||||
res.append(path[:])
|
# 如果当前节点为叶子节点,添加路径到结果中
|
||||||
ways=[]
|
if not (cur.left or cur.right):
|
||||||
if root.left:ways.append(root.left)
|
result.append(path)
|
||||||
if root.right:ways.append(root.right)
|
return
|
||||||
for way in ways:
|
|
||||||
backtrace(way,path)
|
if cur.left:
|
||||||
path.pop()
|
self.traversal(cur.left, path + '->', result)
|
||||||
backtrace(root,path)
|
|
||||||
return ["->".join(list(map(str,i))) for i in res]
|
if cur.right:
|
||||||
|
self.traversal(cur.right, path + '->', result)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
"""二叉树的所有路径 迭代法"""
|
||||||
|
|
||||||
|
def binaryTreePaths(self, root: TreeNode) -> List[str]:
|
||||||
|
# 题目中节点数至少为1
|
||||||
|
stack, path_st, result = deque([root]), deque(), []
|
||||||
|
path_st.append(str(root.val))
|
||||||
|
|
||||||
|
while stack:
|
||||||
|
cur = stack.pop()
|
||||||
|
path = path_st.pop()
|
||||||
|
# 如果当前节点为叶子节点,添加路径到结果中
|
||||||
|
if not (cur.left or cur.right):
|
||||||
|
result.append(path)
|
||||||
|
if cur.right:
|
||||||
|
stack.append(cur.right)
|
||||||
|
path_st.append(path + '->' + str(cur.right.val))
|
||||||
|
if cur.left:
|
||||||
|
stack.append(cur.left)
|
||||||
|
path_st.append(path + '->' + str(cur.left.val))
|
||||||
|
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
```go
|
```go
|
||||||
func binaryTreePaths(root *TreeNode) []string {
|
func binaryTreePaths(root *TreeNode) []string {
|
||||||
|
Reference in New Issue
Block a user