Home Binary Trees - Height of tree
Post
Cancel

Binary Trees - Height of tree

Question

Given a binary tree, write a recursive algorithm to find the height of the tree.

1
2
3
4
5
6
7
8
9
10
11
12
class Node:

    def __init__(self, value) -> None:
        self.value = value 
        self.left = None
        self.right = None

def height(root: Node):
    if root is None:
        # Returning -1 will cancel out with leaf node (+1) to give 0
        return -1 
    return max(height(root.left), height(root.right)) + 1
This post is licensed under CC BY 4.0 by the author.