Find maximum element in binary tree without recursion.
💻 coding

Find maximum element in binary tree without recursion.

1 min read 202 words
1 min read
ShareWhatsAppPost on X
  • 1Level Order Traversal can be used to find the maximum element in a binary tree without recursion.
  • 2The Java implementation utilizes a Queue to traverse the tree and track the maximum value.
  • 3The time complexity of this method is O(n) and the space complexity is O(n) due to the Queue.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Level Order Traversal can be used to find the maximum element in a binary tree without recursion."

Find maximum element in binary tree without recursion.

We could have used either PreOrder, InOrder or PostOrder traversal to find the maximum in a Tree but as it is mentioned that we need to find the maximum without using Recursion.

Using Level Order Traversal we can find the Maximum element. We just need to observe the elements data while deleting.

Java Implementation is as below:

package askgif.tree;

import java.util.LinkedList;
import java.util.Queue;

class Node
{
 int data;
 Node left, right;
 
 public Node(int item)
 {
 data = item;
 left = right = null;
 }
}

class BinaryTree
{
 Node root;
 
 BinaryTree()
 {
 root = null;
 }
 
}

public class TreeQuestions {

	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		Node root = new Node(1);
		binaryTree.root = root;
		binaryTree.root.left = new Node(2);
		binaryTree.root.right = new Node(3);
		
		binaryTree.root.left.left = new Node(4);
		binaryTree.root.left.right = new Node(5);
 
 System.out.println(FindMaxElement(root));

	}

	private static int FindMaxElement(Node treeNode) {
		if(treeNode == null)
			return -1;
		
		Queue<Node> queue = new LinkedList<Node>();
		queue.add(treeNode);
		int max = -1;
		while(!queue.isEmpty()) {
			Node temp = queue.remove();
			if(temp.data > max)
				max = temp.data;
			if(temp.left != null)
				queue.add(temp.left);
			if(temp.right != null)
				queue.add(temp.right);
		}
		
		return max;
	}

}
output:

5

Time Complexity: O(n) as we are traversing through each node once.

Space Complexity: O(n) for Queue.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 16 August 2018 · 1 min read · 202 words

Part of AskGif Blog · coding

You might also like