- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
Latest commit
39 lines (33 loc) · 905 Bytes
/
Copy pathBinaryTree.java
File metadata and controls
39 lines (33 loc) · 905 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
33
34
35
36
37
38
39
importjava.util.Random;
publicclassBinaryTree {
privateintdepth;
privateint[] treeData;
publicBinaryTree(intd) {
// generate simple pseudo-random binary tree with depth as input
depth = d;
treeData = newint[(int)Math.pow(2, depth)-1];
Randomrand = newRandom();
for (inti=0; i<treeData.length; i++){
treeData[i] = rand.nextInt(9);
}
}
publicvoidlistNodesByDepth(){
Stringoutput;
intidx = 0, idxlimit = 0;
for (inti=0; i < depth; i++){
output = "";
idxlimit = idxlimit + (int)Math.pow(2, i);
while (idx < idxlimit ){
output = output + "(" + treeData[idx] + ")";
if(idx < (idxlimit-1) )output = output + ", ";
idx++;
}
System.out.println(output);
}
}
publicstaticvoidmain(String[] args) {
intn = args.length > 0 ? Integer.parseInt(args[0]) : 4;
BinaryTreebtree = newBinaryTree(n);
btree.listNodesByDepth();
}
}