-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path589.java
More file actions
79 lines (73 loc) · 1.92 KB
/
589.java
File metadata and controls
79 lines (73 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
__________________________________________________________________________________________________
sample 1 ms submission
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> ans = new ArrayList<>();
helper(ans,root);
return ans;
}
private void helper(List<Integer> ans, Node node) {
if(node == null) {
return;
}
ans.add(node.val);
for(Node n : node.children) {
helper(ans,n);
}
}
}
__________________________________________________________________________________________________
sample 42344 kb submission
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
helper(root,res);
return res;
}
public void helper(Node root, List<Integer> res){
if(root==null)
return;
Stack<Node> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
Node n = stack.pop();
res.add(n.val);
for(int i=n.children.size()-1;i>=0;i--){
stack.push(n.children.get(i));
}
}
}
public void helper1(Node root, List<Integer> res){
if(root==null)
return;
res.add(root.val);
for(Node c:root.children){
helper1(c,res);
}
}
}
__________________________________________________________________________________________________