Skip to content

Commit dc13984

Browse files
committed
Add question
1 parent 0d10b40 commit dc13984

8 files changed

+88
-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: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import java.util.*;
2+
3+
4+
class Solution {
5+
public List<Integer> preorder(Node root) {
6+
List<Integer> output = new ArrayList<>();
7+
if (root == null) return output;
8+
dfs(root, output);
9+
return output;
10+
}
11+
12+
private void dfs(Node node, List<Integer> output) {
13+
output.add(node.val);
14+
for (Node child : node.children) {
15+
dfs(child, output);
16+
}
17+
}
18+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
var preorder = function(root) {
2+
if (!root) return [];
3+
4+
let output = [];
5+
6+
function dfs(node) {
7+
output.push(node.val);
8+
for (let child of node.children) {
9+
dfs(child);
10+
}
11+
}
12+
13+
dfs(root);
14+
return output;
15+
};
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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 preorder(self, root: 'Node') -> List[int]:
11+
if not root:
12+
return []
13+
14+
output = []
15+
def dfs(node):
16+
output.append(node.val)
17+
for child in node.children:
18+
dfs(child)
19+
20+
dfs(root)
21+
return output
22+
23+
# Time: O(n)
24+
# Space: O(n)
25+
# n is number of nodes in the tree

0 commit comments

Comments
 (0)