Find the Maximum Element in a Binary Tree without using Recursion

Given a binary tree, find the maximum element in it. In this tutorial, we are going to write a code to find the maximum element in a binary tree without using recursion.

For example:

In this binary tree, the maximum element is 9.

Find maximum element in a binary tree.
Find Max in Binary Tree

How do we solve this problem? How we can find the max element in a binary tree? Do we need to visit each node to find the max element?

In a binary tree, we need to visit each node to find the greatest element present in it. So, the idea here is to visit each node to find the maximum element in it.

In this tutorial, I am going to discuss the iterative approach to solve this problem. If you don’t know the difference between recursive and iterative approach. Then, check my previous tutorial in which I have explained recursion vs iteration.

Programming video tutorials

Find Maximum Element in Binary Tree without using Recursion – Java Code

In this example, we are going to use the iterative approach to find the maximum element. For this, we are going to use binary tree level order traversal.

The idea here is to visit each node level by level so that we can keep track of the max element present in a binary tree.

Here are the following steps:

i) Declare a max variable and assign an integer min value.

ii) Declare a queue and add a root node in a queue.


iii) Run a while loop while the queue is not empty and perform the following steps
a) poll a queue and compare the node data with the variable max.
b) Enqueue left and right children of a node if it’s not null.

iv) Once the traversal is complete we get the maximum element.

Find the Max Element in Binary Tree without using Recursion | Video Tutorial

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.