//Recursive Way
public class
BinaryTreeMaxNodeElementR {
class TreeNode {
TreeNode left, right;
int data; // considering integer data.
public TreeNode(int dataItem) {
this.data = dataItem;
left = null;
right = null;
}
}
TreeNode root;
BinaryTreeMaxNodeElementR(){
root = null;
}
public int maxNodeElementBinaryTree(TreeNode
root) {
int maxElement = 0;
if(root != null) {
int leftCount = maxNodeElementBinaryTree(root.left);
int rightCount = maxNodeElementBinaryTree(root.right);
if(leftCount > rightCount) {
maxElement = leftCount;
} else {
maxElement = rightCount;
}
if(root.data > maxElement) {
maxElement = root.data;
}
}
return maxElement;
}
void maxNodeElementBinaryTree(){
int maxElement = maxNodeElementBinaryTree(root);
System.out.println("Count of Binary Tree = " + maxElement);
}
public static void main(String[] args) {
BinaryTreeMaxNodeElementR
binaryTreeMaxNodeElementR = new BinaryTreeMaxNodeElementR();
binaryTreeMaxNodeElementR.root = new TreeNode(1);
binaryTreeMaxNodeElementR.root.left = new TreeNode(2);
binaryTreeMaxNodeElementR.root.right = new TreeNode(3);
binaryTreeMaxNodeElementR.root.left.left = new TreeNode(4);
binaryTreeMaxNodeElementR.root.left.right = new TreeNode(5);
binaryTreeMaxNodeElementR.root.right.left = new TreeNode(6);
binaryTreeMaxNodeElementR.root.right.right = new TreeNode(7);
binaryTreeMaxNodeElementR.maxNodeElementBinaryTree();
}
}
//Time Complexity: O(n). Space Complexity: O(n).
|
Output : 7
Thanks..!!
No comments:
Post a Comment