davegimo

sommaalbero_4

Apr 22nd, 2022
1,075
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 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.     #passo base
  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.     #fase di apparecchiamento
  19.     somma_parziale = a.val
  20.  
  21.  
  22.     #passo ricorsivo
  23.     if a.sx is not None:
  24.         somma_parziale += somma(a.sx)
  25.  
  26.     if a.dx is not None:
  27.         somma_parziale += somma(a.dx)
  28.  
  29.  
  30.     return somma_parziale
  31.    
  32.    
  33.    
  34.  
  35.  
  36.  
  37.  
  38. ###main
  39.  
  40. a = Albero(1)
  41. b = Albero(10)
  42. c = Albero(5)
  43. d = Albero(7)
  44. e = Albero(11)
  45. f = Albero(16)
  46. g = Albero(20)
  47.  
  48.  
  49. a.sx = b
  50. a.dx = c
  51. c.dx = d
  52. b.sx = e
  53. d.sx = f
  54. d.dx = g
  55.  
  56. s = somma(a)
  57. print(s)
  58.  
Advertisement
Add Comment
Please, Sign In to add comment