Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Albero:
- def __init__(self,val):
- self.val = val
- self.sx = None
- self.dx = None
- def somma_nodi(a):
- if a is None:
- return 0
- if a.sx is None and a.dx is None:
- return a.val
- somma = a.val
- if a.sx is not None:
- somma += somma_nodi(a.sx)
- if a.dx is not None:
- somma += somma_nodi(a.dx)
- return somma
- def conta(a):
- if a is None:
- return 0
- if a.sx is None and a.dx is None:
- return 1
- conteggio = 1
- if a.sx is not None:
- conteggio += conta(a.sx)
- if a.dx is not None:
- conteggio += conta(a.dx)
- return conteggio
- def somma_foglie(a):
- if a is None:
- return 0
- if a.sx is None and a.dx is None:
- return a.val
- somma = 0
- if a.sx is not None:
- somma += somma_foglie(a.sx)
- if a.dx is not None:
- somma += somma_foglie(a.dx)
- return somma
- def conta_foglie(a):
- if a is None:
- return 0
- if a.sx is None and a.dx is None:
- return 1
- somma = 0
- if a.sx is not None:
- somma += conta_foglie(a.sx)
- if a.dx is not None:
- somma += conta_foglie(a.dx)
- return somma
- #Dato un albero A, restituire True se il sott.SX ha più nodi foglia del sott.DX, False altrimenti
- def verifica(a):
- conta_foglie_sx = conta_foglie(a.sx)
- conta_foglie_dx = conta_foglie(a.dx)
- if conta_foglie_sx > conta_foglie_dx:
- return True
- else:
- return False
- ################################################################################
- a = Albero(1)
- b = Albero(2)
- c = Albero(3)
- d = Albero(7)
- e = Albero(8)
- f = Albero(11)
- a.sx = b
- a.dx = c
- b.sx = d
- b.dx = e
- c.dx = f
- print("Somma nodi = " + str(somma_nodi(a)))
- print("Conta nodi = " + str(conta(a)))
- print("Somma foglie = " + str(somma_foglie(a)))
- print("Conta foglie = " + str(conta_foglie(a)))
- print(verifica(a))
Advertisement
Add Comment
Please, Sign In to add comment