Given a Binary Search Tree (BST) with duplicates, find the node (the most frequently occurred element) in the given BST. If the BST contains two or more such nodes, print any of them.
Note: We cannot use any extra space. (Assume that the implicit stack space incurred due to recursion does not count)
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
- Both the left and right subtrees must also be binary search trees.
Input : Given BST is 6 / \ 5 7 / \ / \ 4 5 7 7 Output : 7 Input : Given BST is 10 / \ 5 12 / \ / \ 5 6 12 16 Output : 5 or 12 We can print any of the two value 5 or 12.
To find the node, we need to find the Inorder Traversal of the BST because its Inorder Traversal will be in sorted order.
So, the idea is to do recursive Inorder traversal and keeping the track of the previous node. If the current node value is equal to the previous value we can increase the current count and if the current count becomes greater than the maximum count, replace the element.
Below is the implementation of the above approach:
node of BST is 7
Time complexity :
- Find maximum among all right nodes in Binary Tree
- Find the node with maximum value in a Binary Search Tree
- Find the node with maximum value in a Binary Search Tree using recursion
- Count the nodes of a tree whose weighted string does not contain any duplicate characters
- Print all odd nodes of Binary Search Tree
- Print all even nodes of Binary Search Tree
- Leaf nodes from Preorder of a Binary Search Tree
- Pre-Order Successor of all nodes in Binary Search Tree
- Remove all leaf nodes from the binary search tree
- Count the Number of Binary Search Trees present in a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Set 2
- Maximum height of the binary search tree created from the given array
- Sum and Product of minimum and maximum element of Binary Search Tree
- Count nodes with two children at level L in a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.