Given a Binary Search Tree, the task is to find the node with the maximum value in a BST.

For the above tree, we start with 20, then we move right 22, we keep on moving to right until we see NULL. Since right of 22 is NULL, 22 is the node with maximum value.
Approach: This is quite simple. Just traverse the node from root to right recursively until right is NULL. The node whose right is NULL is the node with maximum value.
#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right; }; // Function to create a new node struct node* newNode(int data) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to insert a new node in BST struct node* insert(struct node* node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; } } // Function to find the node with maximum value // i.e. rightmost leaf node int maxValue(struct node* node) { /* loop down to find the rightmost leaf */ struct node* current = node; while (current->right != NULL) current = current->right; return (current->data); } // Driver code int main() { struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); cout << "Maximum value in BST is " << maxValue(root); return 0; } |
Maximum value in BST is 6
Recommended Posts:
- Find the node with minimum value in a Binary Search Tree
- Find the maximum node at a given level in a binary tree
- Search a node in Binary Tree
- Insert a node in Binary Search Tree Iteratively
- Postorder predecessor of a Node in Binary Search Tree
- Get maximum left node in binary tree
- Maximum difference between node and its ancestor in Binary Tree
- Sum and Product of minimum and maximum element of Binary Search Tree
- Find mirror of a given node in Binary tree
- Find the Deepest Node in a Binary Tree
- Find n-th node in Postorder traversal of a Binary Tree
- Find distance from root to given node in a binary tree
- Find n-th node in Preorder traversal of a Binary Tree
- Find the closest element in Binary Search Tree
- Find the closest element in Binary Search Tree | Space Efficient Method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



