Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Albero {
- public int val;
- public Albero sinistro;
- public Albero destro;
- public Albero(int a) {
- val = a;
- }
- public int getVal() {
- return this.val;
- }
- public Albero getSinistro() {
- return this.sinistro;
- }
- public Albero getDestro() {
- return this.destro;
- }
- public void stampa() {
- System.out.println(this.val);
- if (this.getSinistro() != null) {
- this.sinistro.stampa();
- }
- if (this.getDestro() != null) {
- this.destro.stampa();
- }
- }
- public static int somma(Albero a) {
- int tot = a.val;
- if (a.sinistro == null && a.destro == null) { //passo base
- return tot;
- }
- //passo ricorsivo
- if (a.sinistro != null) {
- tot += somma(a.sinistro);
- }
- if (a.destro != null) {
- tot += somma(a.destro);
- }
- return tot;
- }
- public static int conta(Albero a) {
- int c = 1;
- if (a.sinistro == null && a.destro == null) {
- return c;
- }
- if (a.sinistro != null) {
- c += conta(a.sinistro);
- }
- if (a.destro != null) {
- c += conta(a.destro);
- }
- return c;
- }
- public static int contaK(Albero a, int k) {
- int c = 0;
- if (a.val > k) {
- c += 1;
- }
- if (a.sinistro == null && a.destro == null) {
- return c;
- }
- if (a.sinistro != null) {
- c += contaK(a.sinistro,k);
- }
- if (a.destro != null) {
- c += contaK(a.destro,k);
- }
- return c;
- }
- public static void main(String[] args) {
- Albero a = new Albero(2);
- Albero b = new Albero(22);
- Albero c = new Albero(12);
- Albero d = new Albero(10);
- Albero e = new Albero(1);
- Albero f = new Albero(5);
- a.sinistro = b;
- a.destro = c;
- b.sinistro = d;
- b.destro = e;
- c.sinistro = f;
- int x = contaK(a,10);
- System.out.println(x);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement