package in.blogspot.arunj2ee.ds.tree.binary.que;
import in.blogspot.arunj2ee.ds.tree.BinaryTreeNode;
import in.blogspot.arunj2ee.ds.tree.util.BTreePrinter;
import in.blogspot.arunj2ee.ds.tree.util.TreeUtil;
import java.util.LinkedList;
import java.util.Queue;
/*
* Que: Give an algorithm for finding maximum element in binary tree without recursion
* Time Complexity: O(n), Space Complexity: O(n)
*/
public class Que2 {
public static int maxInBinaryTreeLevelOrder(BinaryTreeNode root) {
int max = Integer.MIN_VALUE;
if (root == null)
return max;
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);
while (!q.isEmpty()) {
BinaryTreeNode tmp = q.poll();
if (tmp.getData() > max)
max = tmp.getData();
if (tmp != null) {
if (tmp.getLeft() != null)
q.offer(tmp.getLeft());
if (tmp.getRight() != null)
q.offer(tmp.getRight());
}
}
return max;
}
public static void main(String[] args) {
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
System.out.println("Maximum Value: " + maxInBinaryTreeLevelOrder(rootNode));
}
}
========================================================================
import in.blogspot.arunj2ee.ds.tree.BinaryTreeNode;
import in.blogspot.arunj2ee.ds.tree.util.BTreePrinter;
import in.blogspot.arunj2ee.ds.tree.util.TreeUtil;
import java.util.LinkedList;
import java.util.Queue;
/*
* Que: Give an algorithm for finding maximum element in binary tree without recursion
* Time Complexity: O(n), Space Complexity: O(n)
*/
public class Que2 {
public static int maxInBinaryTreeLevelOrder(BinaryTreeNode root) {
int max = Integer.MIN_VALUE;
if (root == null)
return max;
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);
while (!q.isEmpty()) {
BinaryTreeNode tmp = q.poll();
if (tmp.getData() > max)
max = tmp.getData();
if (tmp != null) {
if (tmp.getLeft() != null)
q.offer(tmp.getLeft());
if (tmp.getRight() != null)
q.offer(tmp.getRight());
}
}
return max;
}
public static void main(String[] args) {
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
System.out.println("Maximum Value: " + maxInBinaryTreeLevelOrder(rootNode));
}
}
========================================================================
Refer Core Classes: http://arunj2ee.blogspot.in/2017/05/tree-core-and-utility-classes.html========================================================================
0 comments:
Post a Comment