Tree: Height of a Binary Tree

  • + 4 comments

    Me using python and implementing level order traversal using arrays to store values of nodes at particular height. List of nodes(n2) are stored in List of tree(n). It will also give you which nodes are present at what level.

    from collections import deque
    def height(root):
        queue=deque()
        queue.append(root)
        n=[]
        n.append([root.info])
        n2=[1]
        while(queue):
            n1=[]
            for i in range(len(n2)):
                current=queue.popleft()
                if(current.left!=None):
                    queue.append(current.left)
                    n1.append(current.left.info)
                if(current.right!=None):
                    queue.append(current.right)
                    n1.append(current.right.info)
            n2=n1
            if(len(n2)!=0):
                n.append(n2)
        return len(n)-1