Size of Binary Tree

Asked

Viewed 781 times

1

I need to develop a method to calculate the size of a Binary Tree but I’m getting compiler error.

Code:

class No:
def __init__(self, dado):
    self.esq = None
    self.dir = None
    self.dado = dado 

class Arvore:
def __init__(self):
    self.raiz = None
def pegarRaiz(self):
    return self.raiz

def inserir(self, val):
    if self.raiz == None:
        self.raiz = No(val)
    else:
        self._inserir(val, self.raiz)

def _inserir(self, val, node):
    if val < node.dado:
        if(node.esq != None):
            self._inserir(val, node.esq)
            node.esq.pai = node
        else:
            node.esq = No(val)
    else:
        if node.dir != None:
            self._inserir(val, node.dir)
            node.dir.pai = node
        else:
            node.dir = No(val)

def Altura(self):
    if self.raiz != None:
        self._Altura(self.raiz)
def _Altura(self,test):
    cont = 0
    if test.dir != None or test.esq != None:
        cont += 1
        self._Altura(test.esq)
        self._Altura(test.dir)
    return cont

T = Arvore()
T.inserir(15)
T.inserir(9)
T.inserir(5)
T.inserir(12)
T.inserir(20)
T.Altura()

Soon after running the code the compiler returns to receive commands, does not show the user the height of the tree.

Some solution?

  • 1

    Ever tried to make print(T.Altura())?

  • Compiler returns "None"

  • 1

    Ah, yes, for in the method Altura you have set no return.

1 answer

1


Instead:

        self._Altura(self.raiz)

Use this:

        return self._Altura(self.raiz)

That is, the word was broken return.

And also here:

        cont = 0

Use this:

        cont = 1

Obviously, there are still some cases where identation is wrong.

  • Putting this Return gets a wrong height for the Tree.

  • @Mrpamonha Use cont = 1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.