#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 30 12:27:19 2018 @author: andrea """ class AlberoBinario: def __init__(self, valore, figliosx=None, figliodx=None): self.v = valore self.sx = figliosx self.dx = figliodx def stampa_percorso(self, cercato): if cercato == self.v: print(self.v) return True else: if self.sx and self.sx.stampa_percorso(cercato): print(self.v) return True elif self.dx and self.dx.stampa_percorso(cercato): print(self.v) return True def __str__(self, livello=0): res = ' '*livello + str(self.v) + "\n" if self.sx: res += self.sx.__str__(livello+1) if self.dx: res += self.dx.__str__(livello+1) return res ''' 0 / 1 / \ 2 3 / /\ 4 5 6 ''' def diametro(self): if not self.sx and not self.dx: return 1, 1 else: if self.sx: hsx, dsx = self.sx.diametro() else: hsx, dsx = 0, 0 if self.dx: hdx, ddx = self.dx.diametro() else: hdx, ddx = 0, 0 print(self.v, '\t', hsx, dsx, hdx, ddx) H = max(hsx, hdx) + 1 D = hsx + hdx +1 return H, max(dsx, ddx, D) if __name__ == '__main__': a = AlberoBinario(4) b = AlberoBinario(5) c = AlberoBinario(6) d = AlberoBinario(2, a) f = AlberoBinario(3, b, c) g = AlberoBinario(1, d, f) h = AlberoBinario(0, g) print(g) #g.stampa_percorso(5) #print(g.diametro()) print(h.diametro())