mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
添加0102.二叉树的层序遍历递归解法Python代码
This commit is contained in:
@ -88,6 +88,7 @@ public:
|
|||||||
python代码:
|
python代码:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
# 迭代法
|
||||||
class Solution:
|
class Solution:
|
||||||
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
||||||
if not root:
|
if not root:
|
||||||
@ -108,7 +109,20 @@ class Solution:
|
|||||||
|
|
||||||
return out_list
|
return out_list
|
||||||
```
|
```
|
||||||
|
```python
|
||||||
|
# 递归法
|
||||||
|
class Solution:
|
||||||
|
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
||||||
|
res = []
|
||||||
|
def helper(root, depth):
|
||||||
|
if not root: return []
|
||||||
|
if len(res) == depth: res.append([]) # start the current depth
|
||||||
|
res[depth].append(root.val) # fulfil the current depth
|
||||||
|
if root.left: helper(root.left, depth + 1) # process child nodes for the next depth
|
||||||
|
if root.right: helper(root.right, depth + 1)
|
||||||
|
helper(root, 0)
|
||||||
|
return res
|
||||||
|
```
|
||||||
java:
|
java:
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
|
Reference in New Issue
Block a user