Skip to content

Commit bbd1b2e

Browse files
author
ironartisan
committed
添加0102.二叉树的层序遍历递归解法Python代码
1 parent b8ef037 commit bbd1b2e

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

problems/0102.二叉树的层序遍历.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ public:
8888
python代码:
8989
9090
```python
91+
# 迭代法
9192
class Solution:
9293
def levelOrder(self, root: TreeNode) -> List[List[int]]:
9394
if not root:
@@ -108,7 +109,20 @@ class Solution:
108109
109110
return out_list
110111
```
111-
112+
```python
113+
# 递归法
114+
class Solution:
115+
def levelOrder(self, root: TreeNode) -> List[List[int]]:
116+
res = []
117+
def helper(root, depth):
118+
if not root: return []
119+
if len(res) == depth: res.append([]) # start the current depth
120+
res[depth].append(root.val) # fulfil the current depth
121+
if root.left: helper(root.left, depth + 1) # process child nodes for the next depth
122+
if root.right: helper(root.right, depth + 1)
123+
helper(root, 0)
124+
return res
125+
```
112126
java:
113127

114128
```Java

0 commit comments

Comments
 (0)