Binary Search Tree (3) and Binary Search Tree
The operation to find the minimum value is very simple. You only need to recursively traverse from the root node to the left subtree node. When the left child of the traversal node is NULL, the node is the minimum value of the tree.
In the preceding tree, the left subtree is recursively traversed from the root node 20 until it is NULL. Because the left subtree of node 4 is NULL, then 4 is the minimum value of the tree.
The minimum value for code query:
Node * minValueNode (Node * node) {Node * current = node; // find the leftmost leaf while (current-> left! = NULL) current = current-> left; return current ;}
Time Complexity: The worst case is O (n)
Similarly, You Can recursively traverse the right subtree until the subtree is NULL to find the maximum value.
Node * maxValueNode (Node * node) {Node * current = node; // find the rightmost leaf while (current-> right! = NULL) current = current-> right; return current ;}
The complete code is as follows:
# Include <iostream> struct Node {int key; Node * left; Node * right ;}; Node * minValueNode (Node * node) {Node * current = node; // find the leftmost leaf while (current-> left! = NULL) current = current-> left; return current;} Node * maxValueNode (Node * node) {Node * current = node; // find the rightmost leaf while (current-> right! = NULL) current = current-> right; return current;} // create a new BST Node * createNewNode (int item) {Node * temp = new Node; temp-> key = item; temp-> left = temp-> right = NULL; return temp;} // insert a new Node to the Node * insert (node * Node, int key) {// empty tree if (node = NULL) return createNewNode (key); // recursive insert. If a specified value already exists, if (key <node-> key) node-> left = insert (node-> left, key) is not inserted ); else if (key> node-> key) node-> right = insert (node-> right, key); // return the unmodified node pointer return node ;} // traverse the Binary Search Tree void inorder (Node * root) {if (root! = NULL) {inorder (root-> left); std: cout <"<root-> key <""; inorder (root-> right) ;}} int main () {/* construct a BST 55/\ 33 77/\ 22 44 66 88 */Node * root = NULL; root = insert (root, 55) as shown below ); insert (root, 33); insert (root, 22); insert (root, 44); insert (root, 77); insert (root, 66); insert (root, 88); Node * result = minValueNode (root); std: cout <"\ n Minimum value in BST is:" <result-> key <std :: endl; result = maxValueNode (root); std: cout <"\ n Maximum value in BST is:" <result-> key <std: endl; return 0 ;}
Output:
Minimum value in BST is: 22
Maximum value in BST is: 88
For more information, see:
Http://cslibrary.stanford.edu/110/BinaryTrees.html