import java util LinkedList import java util Queue import java util St

 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import static java.lang.System.*;
public class Tree_Task20 {
public Node_Task20 root;
public Tree_Task20(int n) {
root = getBalancedTree(n);
}
public static Node_Task20 getBalancedTree(int n) {
if (n == 0) {
return null;
}
else {
int nl = n/2;
int nr = n - nl - 1;
return new Node_Task20(n, getBalancedTree(nl), getBalancedTree(nr));
}
}
public void print() {
printTree(root, 0);
}
private static void printTree(Node_Task20 p, int level) {
if (p != null) {
for (int i = 1; i <= 2*level; i++) {
out.print(" ");
}
out.println(p.getValue());
printTree(p.getLeft(), level + 1);
printTree(p.getRight(), level + 1);
}
}
public int sum() {
Node_Task20 p;
int sum = 0;
Queue<Node_Task20> q = new LinkedList<Node_Task20>();
q.offer(root);
while (!q.isEmpty()) {
p = q.poll();
sum += p.getValue();
if (p.getLeft() != null) {
q.offer(p.getLeft());
}
if (p.getRight() != null) {
q.offer(p.getRight());
}
}
return sum;
}
private int multiply(Node_Task20 p) {
if (p == null) {
return 1;
}
else {
return p.getValue() * multiply(p.getLeft()) * multiply(p.getRight());
}
}
public int mult() {
return multiply(root);
}
public int max() {
Node_Task20 p = root;
int max = root.getValue();
Stack<Node_Task20> s = new Stack<Node_Task20>();
while (p != null || !s.isEmpty()) {
if (p != null) {
if (p.getValue() > max) {
max = p.getValue();
}
if (p.getRight() != null) {
s.push(p.getRight());
}
p = p.getLeft();
}
else {
p = s.pop();
}
}
return max;
}
public static void main(String[] args) {
Tree_Task20 t = new Tree_Task20(12);
t.print();
out.println("Сумма вершин: " + t.sum());
out.println("Произведение вершин: " + t.mult());
out.println("Значение максимального элемента: " + t.max());
}