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 sommaK(Albero a, int k) {
- return sommaKAux(a,1,k);
- }
- public static int sommaKAux(Albero a, int livCorrente, int k) {
- if (livCorrente == k) {
- return a.getVal();
- }
- if (a.getSinistro() == null && a.getDestro() == null) {
- return a.getVal();
- }
- int somma = a.getVal();
- if (a.getSinistro() != null) {
- somma += sommaKAux(a.getSinistro(),livCorrente+1,k);
- }
- if (a.getDestro() != null) {
- somma += sommaKAux(a.getDestro(),livCorrente+1,k);
- }
- return somma;
- }
- 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;
- System.out.println(sommaK(a,2));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement