Skip to content

binary search tree: find largest element in the tree #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 22, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/main/java/com/antesh/dsa/BinarySearchTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static void main(String[] args) {

System.out.print(bst.search(40) ? "\n40 found in BST" : "\n40 not found in BST");
System.out.print(bst.search(90) ? "\n90 found in BST" : "\n90 not found in BST");
System.out.println("\nLargest node in BST: " + bst.findLargestNodeInBST(bst.root));
}

public void insert(int data) {
Expand Down Expand Up @@ -67,6 +68,29 @@ public boolean search(int key) {
return true;
}

public int findLargestNodeInBST(Node node) {
if (node == null) {
System.out.println("Tree is empty");
return 0;
}

int leftMax;
int rightMax;
int max = node.data;

if (node.left != null) {
leftMax = findLargestNodeInBST(node.left);
max = Math.max(max, leftMax);
}

if (node.right != null) {
rightMax = findLargestNodeInBST(node.right);
max = Math.max(max, rightMax);
}

return max;
}

public void inorder(Node node) {
if (node != null) {
inorder(node.left);
Expand Down