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;
/*
* Que: Give an algorithm for finding maximum element in a binary tree
* Using recursion
* Time Complexity: O(n), Space Complexity: O(n)
*/
public class Que1 {
public static int maxInBinaryTree(BinaryTreeNode root) {
int maxValue = Integer.MIN_VALUE;
if (root != null) {
int leftMax = maxInBinaryTree(root.getLeft());
int rightMax = maxInBinaryTree(root.getRight());
if (leftMax > rightMax)
maxValue = leftMax;
else
maxValue = rightMax;
if (root.getData() > maxValue)
maxValue = root.getData();
}
return maxValue;
}
public static void main(String[] args) {
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
System.out.println("Maximum Value: " + maxInBinaryTree(rootNode));
}
}
========================================================================
import in.blogspot.arunj2ee.ds.tree.BinaryTreeNode;
import in.blogspot.arunj2ee.ds.tree.util.BTreePrinter;
import in.blogspot.arunj2ee.ds.tree.util.TreeUtil;
/*
* Que: Give an algorithm for finding maximum element in a binary tree
* Using recursion
* Time Complexity: O(n), Space Complexity: O(n)
*/
public class Que1 {
public static int maxInBinaryTree(BinaryTreeNode root) {
int maxValue = Integer.MIN_VALUE;
if (root != null) {
int leftMax = maxInBinaryTree(root.getLeft());
int rightMax = maxInBinaryTree(root.getRight());
if (leftMax > rightMax)
maxValue = leftMax;
else
maxValue = rightMax;
if (root.getData() > maxValue)
maxValue = root.getData();
}
return maxValue;
}
public static void main(String[] args) {
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
System.out.println("Maximum Value: " + maxInBinaryTree(rootNode));
}
}
========================================================================
Refer Core Classes: http://arunj2ee.blogspot.in/2017/05/tree-core-and-utility-classes.html========================================================================
0 comments:
Post a Comment