Skip to content

Commit 2c27288

Browse files
Merge pull request youngyangyang04#712 from ironartisan/master
添加0102.二叉树的层序遍历递归解法Python代码
2 parents 640a37e + b83cc16 commit 2c27288

File tree

3 files changed

+62
-3
lines changed

3 files changed

+62
-3
lines changed

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

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,9 @@ public:
8787
8888
python代码:
8989
90+
9091
```python3
92+
9193
class Solution:
9294
"""二叉树层序遍历迭代解法"""
9395
@@ -113,7 +115,20 @@ class Solution:
113115
114116
return results
115117
```
116-
118+
```python
119+
# 递归法
120+
class Solution:
121+
def levelOrder(self, root: TreeNode) -> List[List[int]]:
122+
res = []
123+
def helper(root, depth):
124+
if not root: return []
125+
if len(res) == depth: res.append([]) # start the current depth
126+
res[depth].append(root.val) # fulfil the current depth
127+
if root.left: helper(root.left, depth + 1) # process child nodes for the next depth
128+
if root.right: helper(root.right, depth + 1)
129+
helper(root, 0)
130+
return res
131+
```
117132
java:
118133

119134
```Java

problems/0222.完全二叉树的节点个数.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,27 @@ class Solution {
204204
}
205205
}
206206
```
207-
207+
```java
208+
class Solution {
209+
// 迭代法
210+
public int countNodes(TreeNode root) {
211+
if (root == null) return 0;
212+
Queue<TreeNode> queue = new LinkedList<>();
213+
queue.offer(root);
214+
int result = 0;
215+
while (!queue.isEmpty()) {
216+
int size = queue.size();
217+
while (size -- > 0) {
218+
TreeNode cur = queue.poll();
219+
result++;
220+
if (cur.left != null) queue.offer(cur.left);
221+
if (cur.right != null) queue.offer(cur.right);
222+
}
223+
}
224+
return result;
225+
}
226+
}
227+
```
208228
```java
209229
class Solution {
210230
/**

problems/0404.左叶子之和.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,31 @@ class Solution {
201201
}
202202
}
203203
```
204-
204+
```java
205+
// 层序遍历迭代法
206+
class Solution {
207+
public int sumOfLeftLeaves(TreeNode root) {
208+
int sum = 0;
209+
if (root == null) return 0;
210+
Queue<TreeNode> queue = new LinkedList<>();
211+
queue.offer(root);
212+
while (!queue.isEmpty()) {
213+
int size = queue.size();
214+
while (size -- > 0) {
215+
TreeNode node = queue.poll();
216+
if (node.left != null) { // 左节点不为空
217+
queue.offer(node.left);
218+
if (node.left.left == null && node.left.right == null){ // 左叶子节点
219+
sum += node.left.val;
220+
}
221+
}
222+
if (node.right != null) queue.offer(node.right);
223+
}
224+
}
225+
return sum;
226+
}
227+
}
228+
```
205229

206230

207231
## Python

0 commit comments

Comments
 (0)