Skip to content

Commit 0d10b40

Browse files
committed
add question
1 parent 6228ccc commit 0d10b40

4 files changed

+107
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <vector>
2+
#include <queue>
3+
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
vector<vector<int>> levelOrder(Node* root) {
9+
vector<vector<int>> output;
10+
if (!root) return output;
11+
12+
queue<Node*> q;
13+
q.push(root);
14+
15+
while (!q.empty()) {
16+
int n = q.size();
17+
vector<int> level;
18+
for (int i = 0; i < n; i++) {
19+
Node* node = q.front();
20+
q.pop();
21+
level.push_back(node->val);
22+
for (Node* child : node->children) {
23+
q.push(child);
24+
}
25+
}
26+
output.push_back(level);
27+
}
28+
return output;
29+
}
30+
};
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import java.util.*;
2+
3+
4+
class Solution {
5+
public List<List<Integer>> levelOrder(Node root) {
6+
List<List<Integer>> output = new ArrayList<>();
7+
if (root == null) return output;
8+
9+
Queue<Node> q = new LinkedList<>();
10+
q.add(root);
11+
12+
while (!q.isEmpty()) {
13+
int n = q.size();
14+
List<Integer> level = new ArrayList<>();
15+
for (int i = 0; i < n; i++) {
16+
Node node = q.poll();
17+
level.add(node.val);
18+
if (node.children != null) {
19+
q.addAll(node.children);
20+
}
21+
}
22+
output.add(level);
23+
}
24+
return output;
25+
}
26+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
var levelOrder = function(root) {
2+
if (!root) return [];
3+
4+
let output = [];
5+
let q = [root];
6+
7+
while (q.length > 0) {
8+
let n = q.length;
9+
let level = [];
10+
for (let i = 0; i < n; i++) {
11+
let node = q.shift();
12+
level.push(node.val);
13+
if (node.children) {
14+
q.push(...node.children);
15+
}
16+
}
17+
output.push(level);
18+
}
19+
return output;
20+
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
# Definition for a Node.
3+
class Node:
4+
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
5+
self.val = val
6+
self.children = children
7+
"""
8+
9+
class Solution:
10+
def levelOrder(self, root: 'Node') -> List[List[int]]:
11+
if not root:
12+
return []
13+
output = []
14+
q = deque()
15+
q.append(root)
16+
17+
while q:
18+
n = len(q)
19+
level = []
20+
for _ in range(n):
21+
node = q.popleft()
22+
level.append(node.val)
23+
for child in node.children:
24+
q.append(child)
25+
output.append(level)
26+
27+
return output
28+
29+
# Time: O(n)
30+
# Space: O(n)
31+
# n is number of nodes in the tree

0 commit comments

Comments
 (0)