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))
OutputMaximum 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.
Implementation
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))
OutputMaximum Depth of the Binary Tree: 3
Time Complexity: O(n)
Space Complexity: O(n)
Similar Reads
JavaScript Program to Find Maximum Width of Binary Tree
The maximum width of a given binary tree can be calculated by finding the maximum of all the level widths. The maximum width of a Binary tree is the maximum number of nodes present at any level. The maximum width of the Binary tree will include only the present node and not include null nodes. The m
4 min read
Height and Depth of a node in a Binary Tree
Given a Binary Tree consisting of n nodes and a integer k, the task is to find the depth and height of the node with value k in the Binary Tree.Note:The depth of a node is the number of edges present in path from the root node of a tree to that node. The height of a node is the maximum number of edg
15 min read
Find the maximum element of every subtree of a Binary Tree
Given a Binary Tree, find the maximum element of every subtree of it. Examples :Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : [4, 5, 5, 7, 6, 7, 7] Explanation: The maximum element of the subtree rooted at node 4 is 4. The maximum element of the subtree rooted at node 2 is 5. The maximum element of the
15+ min read
Maximum in a Binary Search Tree
Given a Binary Search Tree, the task is to find the node with the maximum value in a BST.Example:Input:Output : 7Input:Output: 20Table of Content[Naive Approach] Using Inorder Traversal â O(n) Time and O(n) Space[Expected Approach] Iterative Approach â O(n) Time and O(1) Space[Naive Approach] Using
11 min read
Python Program for Maximum height when coins are arranged in a triangle
We have N coins which need to arrange in form of a triangle, i.e. first row will have 1 coin, second row will have 2 coins and so on, we need to tell maximum height which we can achieve by using these N coins. Examples: Input : N = 7Output : 3Explanation: Maximum height will be 3, putting 1, 2 and t
3 min read
PyQtGraph â Getting Maximum Height of Plot Window
In this article we will see how we can get the maximum height of the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interact
3 min read
Maximum value of Bitwise AND from root to leaf in a Binary tree
Given a Binary Tree, the task is to find the maximum value of Bitwise AND from any path from the root node to the leaf node. Examples: Input: Below is the given graph: Output: 7Explanation:path 1: 15->3->5 = (15 & 3 & 5) = 1path 2: 15->3->1 =(15 & 3 & 1) = 1path 3: 15-
7 min read
Construct a Perfect Binary Tree with given Height
Given an integer N, the task is to generate a perfect binary tree with height N such that each node has a value that is the same as its depth. Return the inorder traversal of the generated binary tree. A Perfect binary tree is a type of binary tree where every internal node has exactly two child nod
9 min read
Find maximum GCD value from root to leaf in a Binary tree
Given a Binary Tree, the task is to find the maximum value of GCD from any path from the root node to the leaf node. Examples: Input: Below is the given tree: Output: 3Explanation:Path 1: 15->3->5 = gcd(15, 3, 15) =3Path 2: 15->3->1 =gcd(15, 3, 1) = 1Path 3: 15->7->31=gcd(15, 7, 31
8 min read
Maximizing Robbery in Binary Tree Houses without Alerting Police
There are Houses arranged in the form of a Binary tree. There is only one entrance to the houses which is the root of a tree. It will automatically contact the police if two directly linked houses are broken into on the same night. Given the root of the binary tree, return the maximum amount of mone
11 min read