davegimo

alberopyfederica

Mar 10th, 2021
466
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class BinaryTree:
  2.  
  3.     def __init__(self, val):
  4.         self.left = None
  5.         self.right = None
  6.         self.val = val
  7.  
  8.  
  9.     def getRight(self):
  10.         return self.right
  11.  
  12.     def getLeft(self):
  13.         return self.left
  14.  
  15.     def getVal(self):
  16.         return self.val
  17.  
  18. def sommaNodi(a):
  19.  
  20.     if a.getRight() == None and a.getLeft() == None: #è fogliaa!!!!
  21.         return a.getVal()
  22.  
  23.     somma = a.getVal()
  24.        
  25.     if a.getLeft() != None:
  26.         somma += sommaNodi(a.getLeft())
  27.  
  28.     if a.getRight() != None:
  29.         somma += sommaNodi(a.getRight())
  30.  
  31.     return somma
  32.  
  33. def contaNodi(a):
  34.  
  35.     if a.getRight() == None and a.getLeft() == None: #è fogliaa!!!!
  36.         return 1
  37.  
  38.    
  39.     conta = 1
  40.        
  41.     if a.getLeft() != None:
  42.         conta += contaNodi(a.getLeft())
  43.  
  44.     if a.getRight() != None:
  45.         conta += contaNodi(a.getRight())
  46.  
  47.     return conta
  48.  
  49. def contaNodiPari(a):
  50.  
  51.     if a.getVal() % 2 == 0:
  52.         conta = 1
  53.     else:
  54.         conta = 0
  55.  
  56.        
  57.     if a.getRight() == None and a.getLeft() == None: #è fogliaa!!!!
  58.         return conta
  59.  
  60.        
  61.     if a.getLeft() != None:
  62.         conta += contaNodiPari(a.getLeft())
  63.  
  64.     if a.getRight() != None:
  65.         conta += contaNodiPari(a.getRight())
  66.  
  67.     return conta
  68.        
  69.  
  70.  
  71. a = BinaryTree(4)
  72. b = BinaryTree(1)
  73. c = BinaryTree(3)
  74. d = BinaryTree(5)
  75. dd = BinaryTree(55)
  76.  
  77. a.left = b
  78. a.right = c
  79. c.right = d
  80. d.left = dd
  81.  
  82. print(contaNodiPari(a))
  83.  
RAW Paste Data