-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathN_ary.java
More file actions
55 lines (45 loc) · 1.52 KB
/
N_ary.java
File metadata and controls
55 lines (45 loc) · 1.52 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
package Trees;
import java.util.*;
public class N_ary<E> {
public class Node<T extends E> {
T val;
ArrayList<Node> list;
public Node(T val, ArrayList<Node> list) {
this.val = val;
this.list = list;
}
}
public List<E> preOrder(Node root) {
if (root == null) {
return new ArrayList<>();
}
List<E> ans = new ArrayList<>();
ans.add((E) root.val);
root.list.forEach(item -> {
ans.addAll(preOrder((Node) item));
});
return ans;
}
public List<E> postOrder(Node root) {
if (root == null) {
return new ArrayList<>();
}
List<E> ans = new ArrayList<>();
root.list.forEach((item) -> {
ans.addAll(postOrder((Node) item));
});
ans.add((E) root.val);
return ans;
}
public static void main(String[] args) {
N_ary<Integer> tree = new N_ary<>();
N_ary.Node node4 = tree.new Node<>(5, new ArrayList<>());
N_ary.Node node5 = tree.new Node<>(6, new ArrayList<>());
N_ary.Node node1 = tree.new Node<>(3, new ArrayList<>(Arrays.asList(node4, node5)));
N_ary.Node node2 = tree.new Node<>(2, new ArrayList<>());
N_ary.Node node3 = tree.new Node<>(4, new ArrayList<>());
N_ary.Node root = tree.new Node<>(1, new ArrayList<>(Arrays.asList(node1, node2, node3)));
System.out.println(tree.preOrder(root));
System.out.println(tree.postOrder(root));
}
}