Tree: Height of a Binary Tree

  • + 0 comments
    def height(root):
        '''
        Solved with BFS, this is adapt to get shortest distances in tree with edges weight=1
        '''
        explored = {}
        explored[root.info] = 0
        q = deque()
        q.append(root)
        height_tree = 0
        while q:
            v = q.popleft()
            children = []
            if v.left:
                children.append(v.left)
            if v.right:
                children.append(v.right)
            for w in children:
                if not explored.get(w.info) and (w.info not in explored):
                    explored[w.info] = explored[v.info] + 1
                    height_tree = max(explored[w.info], height_tree)
                    q.append(w)
        return height_tree