davegimo

albero somma

Aug 17th, 2023
962
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. class Albero:
  2.     def __init__(self, val):  
  3.         self.val = val
  4.         self.sx = None
  5.         self.dx = None
  6.  
  7.        
  8. a = Albero(8)
  9. b = Albero(3)
  10. c = Albero(10)
  11. d = Albero(1)
  12. e = Albero(6)
  13. f = Albero(4)
  14. g = Albero(7)
  15. h = Albero(14)
  16. i = Albero(13)
  17.  
  18.  
  19. a.sx = b
  20. a.dx = c
  21. b.sx = d
  22. b.dx = e
  23. e.sx = f
  24. e.dx = g
  25. c.dx = h
  26. h.sx = i
  27.  
  28.  
  29.  
  30. def sommaNodi(a):
  31.     if a is None:
  32.         return 0
  33.    
  34.     if a.sx is None and a.dx is None:
  35.         return a.val
  36.  
  37.     somma = a.val
  38.  
  39.     if a.sx is not None:
  40.         somma += sommaNodi(a.sx)
  41.        
  42.     if a.dx is not None:
  43.         somma += sommaNodi(a.dx)
  44.  
  45.     return somma
  46.  
  47.  
Advertisement
Add Comment
Please, Sign In to add comment