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); } } //Task 20c - найти сумму веришин public int sum() { Node_Task20 p; int sum = 0; Queue q = new LinkedList(); 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; } //Task 20c - произведение вершин 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); } //Task 20c - максимум среди вершин public int max() { Node_Task20 p = root; int max = root.getValue(); Stack s = new Stack(); 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()); }