Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Albero:
- def __init__(self, v): #costruttore
- self.val = v
- self.sx = None
- self.dx = None
- def cerca(a,valore):
- if a is None:
- return False
- if a.val == valore:
- return True
- if a.sx is None and a.dx is None:
- return False
- cerca_sx = False
- cerca_dx = False
- if a.sx is not None:
- cerca_sx = cerca(a.sx,valore)
- if a.dx is not None:
- cerca_dx = cerca(a.dx,valore)
- if cerca_sx is True or cerca_dx is True:
- return True
- return False
- #scrivere funzione controlla_somma(A,B) dove
- #dati due alberi A e B ritorno true se la somma dei loro nodi coincide
- def controlla_somma(A,B):
- somma_A = somma(A)
- somma_B = somma(B)
- if somma_A == somma_B:
- return True
- return False
- def somma(a):
- if a is None:
- return 0
- if a.sx is None and a.dx is None:
- return a.val
- s = a.val
- if a.sx is not None:
- s += somma(a.sx)
- if a.dx is not None:
- s += somma(a.dx)
- return s
- #Dato un albero, definire funzione somma_liv(a,livello)
- #sommare tutti i nodi il cui livello รจ liv
- def somma_liv(a,livello):
- return somma_con_livello(a,livello,0)
- def somma_con_livello(a,livello,livello_corrente):
- if a is None:
- return 0
- if livello == livello_corrente:
- return a.val
- if a.sx is None and a.dx is None:
- return 0
- somma = 0
- if a.sx is not None:
- somma += somma_con_livello(a.sx,livello,livello_corrente + 1)
- if a.dx is not None:
- somma += somma_con_livello(a.dx,livello,livello_corrente + 1)
- return somma
- #Definire la funziona somma_con_livello_pari
- ###main
- a = Albero(8)
- b = Albero(3)
- c = Albero(10)
- d = Albero(1)
- e = Albero(6)
- f = Albero(14)
- g = Albero(4)
- h = Albero(7)
- i = Albero(13)
- a.sx = b
- a.dx = c
- c.dx = f
- b.sx = d
- b.dx = e
- e.sx = g
- e.dx = h
- f.sx = i
- #flag = cerca(a,20)
- #print(flag)
- x = Albero(70)
- print(somma_liv(a,3))
- #print(controlla_somma(a,x))
Advertisement
Add Comment
Please, Sign In to add comment