Advertisement
davegimo

Untitled

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