mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Merge branch 'master' of github.com:youngyangyang04/leetcode-master
This commit is contained in:
@@ -271,6 +271,36 @@ func levelOrder(root *TreeNode) [][]int {
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
102. 二叉树的层序遍历:使用切片模拟队列,易理解
|
||||
*/
|
||||
func levelOrder(root *TreeNode) (res [][]int) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
|
||||
curLevel := []*TreeNode{root} // 存放当前层节点
|
||||
for len(curLevel) > 0 {
|
||||
nextLevel := []*TreeNode{} // 准备通过当前层生成下一层
|
||||
vals := []int{}
|
||||
|
||||
for _, node := range curLevel {
|
||||
vals = append(vals, node.Val) // 收集当前层的值
|
||||
// 收集下一层的节点
|
||||
if node.Left != nil {
|
||||
nextLevel = append(nextLevel, node.Left)
|
||||
}
|
||||
if node.Right != nil {
|
||||
nextLevel = append(nextLevel, node.Right)
|
||||
}
|
||||
}
|
||||
res = append(res, vals)
|
||||
curLevel = nextLevel // 将下一层变成当前层
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
javascript代码:
|
||||
@@ -1072,7 +1102,6 @@ public class N0637 {
|
||||
|
||||
que.offerLast(root);
|
||||
while (!que.isEmpty()) {
|
||||
TreeNode peek = que.peekFirst();
|
||||
|
||||
int levelSize = que.size();
|
||||
double levelSum = 0.0;
|
||||
@@ -1346,6 +1375,22 @@ class Solution:
|
||||
return results
|
||||
```
|
||||
|
||||
```python
|
||||
# LeetCode 429. N-ary Tree Level Order Traversal
|
||||
# 递归法
|
||||
class Solution:
|
||||
def levelOrder(self, root: 'Node') -> List[List[int]]:
|
||||
if not root: return []
|
||||
result=[]
|
||||
def traversal(root,depth):
|
||||
if len(result)==depth:result.append([])
|
||||
result[depth].append(root.val)
|
||||
if root.children:
|
||||
for i in range(len(root.children)):traversal(root.children[i],depth+1)
|
||||
|
||||
traversal(root,0)
|
||||
return result
|
||||
```
|
||||
java:
|
||||
|
||||
```java
|
||||
@@ -2955,7 +3000,7 @@ impl Solution {
|
||||
* 107.二叉树的层次遍历II
|
||||
* 199.二叉树的右视图
|
||||
* 637.二叉树的层平均值
|
||||
* 429.N叉树的前序遍历
|
||||
* 429.N叉树的层序遍历
|
||||
* 515.在每个树行中找最大值
|
||||
* 116.填充每个节点的下一个右侧节点指针
|
||||
* 117.填充每个节点的下一个右侧节点指针II
|
||||
@@ -2970,3 +3015,4 @@ impl Solution {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user