Maximum Depth or Height Of a Binary Tree with python

Last Updated : 22 Jan, 2024

Binary trees are hierarchical data structures that have widespread applications in computer science, from databases to graphics. One essential property of a binary tree is its depth or height. In this article, we’ll discuss how to compute the maximum depth (or height) of a binary tree using Python.

What is the Maximum Depth or Height?

The maximum depth or height of a binary tree is the number of edges on the longest path from the root node down to the farthest leaf node. A tree with a single node (only the root) has a height of 0.

Recursive Approach to Find the Maximum Depth of a Binary Tree with Python

Here, we will be using a recursive approach to calculate the maximum depth or height of a binary tree. In this method, we make a recursive call again and again until the base case is reached.

Algorithm:

Step 1: Base Case – Empty Tree

• Check if the current node is None. If it is, this means the tree is empty or we’ve reached the end of a branch.
• In such a case, return 0 because an empty tree has a height of 0.

Step 2: Recursive Case – Non-Empty Tree

• If the current node is not None, calculate the depth of the left and right subtrees.
• Call maxDepth(node.left) to find the depth of the left subtree.
• Call maxDepth(node.right) to find the depth of the right subtree.

Step 3: Calculate and Return Maximum Depth

• Use the max() function to determine the greater depth between the left and right subtrees.
• Add 1 to the maximum depth value to account for the current node’s depth.
• Return this value.

Implementation:

To determine the height of a binary tree, we can use a recursive approach. Starting from the root, the height of the tree is the maximum of the heights of its left and right subtrees, plus one (for the root itself).

Python3

 `class` `Node:` `    ``def` `__init__(``self``, value``=``0``, left``=``None``, right``=``None``):` `        ``self``.data ``=` `value` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `def` `maxDepth(node):` `    ``if` `node ``is` `None``:` `        ``return` `0` `    ``else``:` `        ``left_depth ``=` `maxDepth(node.left)` `        ``right_depth ``=` `maxDepth(node.right)` `        ``return` `max``(left_depth, right_depth) ``+` `1`   `# Test case` `if` `__name__ ``=``=` `"__main__"``:` `    ``# Constructing the tree` `    ``root ``=` `Node(``1``)` `    ``root.left ``=` `Node(``2``)` `    ``root.right ``=` `Node(``3``)` `    ``root.left.left ``=` `Node(``4``)` `    ``root.left.right ``=` `Node(``5``)` `    ``root.left.left.left ``=` `Node(``6``)` `    `  `    ``# Printing the depth` `    ``print``(``"Maximum Depth of the Binary Tree:"``, maxDepth(root))`

Output

```Maximum Depth of the Binary Tree: 4

```

Time Complexity: Time complexity of above code is O(n) as we visit the each node of a binary search tree once.
Space Complexity: Space complexity of above code is also O(n) because of recursive call stack and the recursive calls are equal to the total numbers of nodes in a binary tree.

Find the Maximum Depth of a Binary Tree Using Level Order Traversal with Python

To find the maximum depth of a binary tree using an iterative approach in Python, we typically use a breadth-first search (BFS) strategy. This approach involves traversing the tree level by level and keeping track of the depth as we go. A common way to implement BFS is by using a queue.

Algorithm:

Step 1: Firstly we check if the root of the binary tree is “None”. If it is None, return 0 because an empty tree has a depth of zero.

Step 2: Initialize a queue to store pairs of tree nodes and their corresponding depth levels. Begin with the root node of the tree, assigning it a depth of 1.

Step 3: Create a variable “max_depth” and set it to 0. This variable will be used to track the maximum depth of the tree as we iterate through it.

Step 4: While the queue is not empty, repeat the following steps:

• Remove the front element from the queue. This element will be a tuple containing a node from the tree (“current_node”) and its depth (“depth”).
• Update the “max_depth” variable with the depth of “current_node” if it is greater than the current “max_depth”.
• If “current_node” has a left child, add this child to the queue with a depth of “depth + 1”.
• If “current_node” has a right child, also add this child to the queue with a depth of “depth + 1”.

Step 5: Continue the process of removing nodes from the queue, updating the maximum depth, and adding child nodes to the queue until the queue is empty.

Step 6: After the queue is empty, which means all nodes have been processed, the value of “max_depth” will represent the maximum depth of the tree.

Step 7: Return this value.

Python3

 `class` `TreeNode:` `    ``def` `__init__(``self``, value``=``0``, left``=``None``, right``=``None``):` `        ``self``.value ``=` `value` `        ``self``.left ``=` `left` `        ``self``.right ``=` `right`   `def` `maxDepth(root):` `    ``if` `not` `root:` `        ``return` `0` `    ``# Initialize a queue with the root node and its depth` `    ``queue ``=` `[(root, ``1``)]  ` `    ``max_depth ``=` `0`   `    ``while` `queue:` `        ``# Dequeue the front element` `        ``current_node, depth ``=` `queue.pop(``0``)  `   `        ``# Update the maximum depth` `        ``max_depth ``=` `max``(max_depth, depth)`   `        ``# Enqueue the child of the current node with their corresponding depth` `        ``if` `current_node.left:` `            ``queue.append((current_node.left, depth ``+` `1``))` `        ``if` `current_node.right:` `            ``queue.append((current_node.right, depth ``+` `1``))`   `    ``return` `max_depth`   `# Test case` `if` `__name__ ``=``=` `"__main__"``:` `  `  `    ``# Constructing the tree` `    ``root ``=` `TreeNode(``1``)` `    ``root.left ``=` `TreeNode(``2``)` `    ``root.right ``=` `TreeNode(``3``)` `    ``root.left.left ``=` `TreeNode(``4``)` `    ``root.left.right ``=` `TreeNode(``5``)`   `    ``print``(``"Maximum Depth of the Binary Tree:"``, maxDepth(root))`

Output

```Maximum Depth of the Binary Tree: 3

```

Time Complexity: O(n)
Space Complexity: O(n)

Previous
Next