Advertisement
davegimo

franc3

Mar 11th, 2021
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. public class Albero {
  2.  
  3.         public int val;
  4.         public Albero sinistro;
  5.         public Albero destro;
  6.  
  7.         public Albero(int a) {
  8.             val = a;
  9.         }
  10.  
  11.         public int getVal() {
  12.             return this.val;
  13.         }
  14.  
  15.         public Albero getSinistro() {
  16.             return this.sinistro;
  17.         }
  18.  
  19.         public Albero getDestro() {
  20.             return this.destro;
  21.         }
  22.  
  23.  
  24.  
  25.     public void stampa() {
  26.  
  27.         System.out.println(this.val);
  28.  
  29.         if (this.getSinistro() != null) {
  30.             this.sinistro.stampa();
  31.         }
  32.  
  33.  
  34.         if (this.getDestro() != null) {
  35.             this.destro.stampa();
  36.         }
  37.     }
  38.    
  39.    
  40.     public static int sommaK(Albero a, int k) {
  41.         return sommaKAux(a,1,k);
  42.     }
  43.    
  44.     public static int sommaKAux(Albero a, int livCorrente, int k) {
  45.        
  46.         if (livCorrente == k) {
  47.             return a.getVal();
  48.         }
  49.        
  50.         if (a.getSinistro() == null && a.getDestro() == null) {
  51.             return a.getVal();
  52.         }
  53.        
  54.         int somma = a.getVal();
  55.        
  56.         if (a.getSinistro() != null) {
  57.             somma += sommaKAux(a.getSinistro(),livCorrente+1,k);
  58.         }
  59.        
  60.         if (a.getDestro() != null) {
  61.             somma += sommaKAux(a.getDestro(),livCorrente+1,k);
  62.         }
  63.        
  64.        
  65.         return somma;
  66.        
  67.        
  68.        
  69.     }
  70.    
  71.  
  72.     public static void main(String[] args) {
  73.        
  74.        
  75.         Albero a = new Albero(2);
  76.         Albero b = new Albero(22);
  77.         Albero c = new Albero(12);
  78.         Albero d = new Albero(10);
  79.         Albero e = new Albero(1);
  80.         Albero f = new Albero(5);
  81.  
  82.         a.sinistro = b;
  83.         a.destro = c;
  84.  
  85.         b.sinistro = d;
  86.         b.destro = e;
  87.  
  88.         c.sinistro = f;
  89.        
  90.         System.out.println(sommaK(a,2));
  91.        
  92.  
  93.  
  94.     }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement