Questo è un metodo della classe, quindi è necessario chiamarlo da un'istanza (self
) o dalla classe stessa. Anche se non funzionerà come credi, a meno che non lo definisci come staticmethod
o cambi la tua chiamata, ad es.
def height(self):
return 1 + max(self.left.height() if self.left is not None else 0,
self.right.height() if self.right is not None else 0)
o
@staticmethod
def height(self):
return 1 + max(self.height(self.left) if self.left is not None else 0,
self.height(self.right) if self.right is not None else 0)
Si noti, che non si dovrebbe usare ==
da confrontare con None
(complimenti a timgeb). E devi verificare se esistono anche i nodi figli. E il tuo algoritmo non funziona, quindi l'ho modificato leggermente.
Esempio:
class Node:
def __init__(self, root=None, left=None, right=None):
self.root = root
self.left = left
self.right = right
def height(self):
return 1 + max(self.left.height() if self.left is not None else 0,
self.right.height() if self.right is not None else 0)
# Create a binary tree of height 4 using the binary-heap property
tree = [Node() for _ in range(10)]
root = tree[0]
for i in range(len(tree)):
l_child_idx, r_child_idx = (i + 1) * 2 - 1, (i + 1) * 2
root_idx = (i + 1) // 2
if root_idx:
tree[i].root = tree[root_idx]
if l_child_idx < len(tree):
tree[i].left = tree[l_child_idx]
if r_child_idx < len(tree):
tree[i].right = tree[r_child_idx]
print(root.height()) # -> 4
fonte
2016-04-08 13:05:01
È inoltre necessario sostituire 'self.root == None' con' self.root è None'. – timgeb
Non sono sicuro di seguirlo. Né in Python2 né in 3 otterrete un controllo degli errori per "Nessuno" in questo modo. – timgeb
@timgeb Oh, scusate, pensavo che ne avessero fatto un errore in Python 3. Sto usando Python 2 la maggior parte del tempo, quindi mi dispiace per l'equivoco. –