Binary Tree Size function in Python -
i have written couple of functions calculate size of binary tree. first 1 (function 1) works fine , declared outside class, not member function of class. second 1 member function of class giving me weird results. confused! appreciated.
function 1 def size(root): if root none: return 0 else: return size(root.left)+ 1+ size(root.right) function 2 def size(self): if self.left none or self.right none: return 0 else: return self.left.size()+1+self.right.size()
if self.left none or self.right none:
if 1 of them none, return 0
you need @ least size of right + 1 if left none
i think need :
leftsize = self.left.size() if self.left else 0 rightsize = self.right.size() if self.right else 0 return leftsize + 1 + rightsize
i havent tried it.
Comments
Post a Comment