-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGeneric tree constructor
More file actions
32 lines (28 loc) · 866 Bytes
/
Generic tree constructor
File metadata and controls
32 lines (28 loc) · 866 Bytes
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
package com.company;
import java.util.ArrayList;
import java.util.Stack;
public class constructorr {
public static void main(String[] args) {
Node root;
int arr[] = {10, 20, 50, -1, 60, -1, -1, 30, 70, -1, 80, 110, -1, 120, -1, -1, 90, -1, -1, 40, 100, -1, -1, -1};
Stack<Node> st = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
st.pop();
} else {
Node t = new Node();
t.data = arr[i];
if (st.size() > 0) {
st.peek().children.add(t);
} else {
root = t;
}
st.push(t);
}
}
}
private class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}
}