//Iterative Way: Non-Recursive Way
public class BinaryTreeMaxNodeElementIterativeModel {
class TreeNode {
TreeNode left, right;
int data; // considering integer data.
public TreeNode(int dataItem) {
this.data = dataItem;
left = null;
right = null;
}
}
TreeNode root;
BinaryTreeMaxNodeElementIterativeModel(){
root = null;
}
public int maxNodeElementBinaryTree(TreeNode
root) {
int maxElement = 0;
if(root != null) {
Queue<TreeNode>
q = new LinkedList<TreeNode>();
q.offer(root); // Add root to queue.
while(!q.isEmpty()) {
TreeNode
temp = q.poll(); // Remove an element from queue.
if(temp.data > maxElement) {
maxElement = temp.data;
}
if(temp.left != null) {
q.offer(temp.left);
}
if(temp.right != null) {
q.offer(temp.right);
}
}
}
return maxElement;
}
void maxNodeElementBinaryTree(){
int maxElement = maxNodeElementBinaryTree(root);
System.out.println("Count of Binary Tree = " + maxElement);
}
public static void main(String[] args) {
BinaryTreeMaxNodeElementIterativeModel
binaryTreeMaxNodeElementIterativeModel = new BinaryTreeMaxNodeElementIterativeModel();
binaryTreeMaxNodeElementIterativeModel.root = new TreeNode(1);
binaryTreeMaxNodeElementIterativeModel.root.left = new TreeNode(2);
binaryTreeMaxNodeElementIterativeModel.root.right = new TreeNode(3);
binaryTreeMaxNodeElementIterativeModel.root.left.left = new TreeNode(4);
binaryTreeMaxNodeElementIterativeModel.root.left.right = new TreeNode(5);
binaryTreeMaxNodeElementIterativeModel.root.right.left = new TreeNode(6);
binaryTreeMaxNodeElementIterativeModel.root.right.right = new TreeNode(7);
binaryTreeMaxNodeElementIterativeModel.maxNodeElementBinaryTree();
}
}
|
Output : 7
Thanks..!!