Tree: Height of a Binary Tree

Sort by

recency

|

969 Discussions

|

  • + 1 comment

    You muppets. The javascript implementation contains all nodes in the right. Creating a right skewed tree.

    e.g.

    {
        "data": 3,
        "left": null,
        "right": {
            "data": null,
            "left": null,
            "right": {
                "data": null,
                "left": null,
                "right": {
                    "data": null,
                    "left": null,
                    "right": {
                        "data": null,
                        "left": null,
                        "right": null
                    }
                }
            }
        }
    }
    
  • + 0 comments
    def height(root):
        queue = deque([root])
        height = -1
    
        while queue:
            level_len = len(queue)
            height += 1
    
            for _ in range(level_len):
                current = queue.popleft()
                if current.left:
                    queue.append(current.left)
                if current.right:
                    queue.append(current.right)
        
        return height
    
  • + 2 comments

    Typescript missing boilerplate

  • + 1 comment

    C# missing boilerplate

  • + 0 comments

    PYTHON solution

    def height(root):
        left_h, right_h = 0, 0
        if root.left:
            left_h = 1 + height(root.left)
        if root.right:
            right_h = 1 + height(root.right)
        return max(left_h, right_h)