Created
November 27, 2016 06:39
-
-
Save nilaydshah/bd9b55a515adf4def82dcf36cfb616c6 to your computer and use it in GitHub Desktop.
Finding maximum element in binary tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FindMaxInBinaryTree { | |
// find max element in binary tree recursively | |
public int findMax(BinaryTreeNode root) { | |
int root_val, left, regith, max = 0; | |
if(root != null) { | |
root_val = root.getData(); | |
left = findMax(root.getLeft()); | |
right = findMax(root.getRight()); | |
// find the largest of the three values. | |
if(left > right) | |
max = left; | |
else | |
max = right; | |
if(root_val > max) | |
max = root_val; | |
} | |
return max; | |
} | |
// find max element in binary tree non-recursively using level order traversal | |
public int findMaxUsingLevelOrder(BinaryTreeNode root) { | |
BinaryTreeNode temp; | |
int max = 0; | |
LLQueue<BinaryTreeNode> q = new LLQueue<BinaryTreeNode>(); | |
q.enqueue(root); | |
while(!q.isEmpty()) { | |
temp = q.dequeue(); | |
//largest of the three values | |
if(max < temp.getData()) | |
max = temp.getData(); | |
if(temp.getLeft()) | |
q.enqueue(temp.getLeft()); | |
if(temp.getRight()) | |
q.enqueue(temp.getRight()); | |
} | |
q.deleteQueue(); | |
return max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment