Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 0102.二叉树的层序遍历.md Python层序遍历递归法更简洁 #2553

Merged
merged 1 commit into from
Jun 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 17 additions & 11 deletions problems/0102.二叉树的层序遍历.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ class Solution:
return result
```
```python
# 递归法
#递归法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
Expand All @@ -210,18 +210,24 @@ class Solution:
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []

levels = []
self.helper(root, 0, levels)

def traverse(node, level):
if not node:
return

if len(levels) == level:
levels.append([])

levels[level].append(node.val)
traverse(node.left, level + 1)
traverse(node.right, level + 1)

traverse(root, 0)
return levels

def helper(self, node, level, levels):
if not node:
return
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
self.helper(node.left, level + 1, levels)
self.helper(node.right, level + 1, levels)

```

Expand Down