📜  在二分搜索树中查找最大重复节点数

📅  最后修改于: 2021-05-24 21:25:10             🧑  作者: Mango

给定具有重复项的二叉搜索树(BST),在给定的BST中查找节点(最常出现的元素)。如果BST包含两个或更多这样的节点,请打印它们中的任何一个。

注意:我们不能使用任何多余的空间。 (假设由于递归导致的隐式堆栈空间不计算在内)

假设BST定义如下:

  • 节点的左子树仅包含键小于或等于该节点的键的节点。
  • 节点的右子树仅包含键大于或等于节点的键的节点。
  • 左子树和右子树都必须也是二进制搜索树。

例子:

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.

方法:

要找到该节点,我们需要找到BST的有序遍历,因为其有序遍历将按排序顺序进行。

因此,该想法是进行递归有序遍历并保持对先前节点的跟踪。如果当前节点值等于先前的值,我们可以增加当前计数,如果当前计数大于最大计数,则替换该元素。

下面是上述方法的实现:

C++
/* C++ program to find the median of BST in O(n) 
   time and O(1) space*/
  
#include 
using namespace std;
  
/* A binary search tree Node has data, pointer
   to left child and a pointer to right child */
  
struct Node {
    int val;
    struct Node *left, *right;
};
  
struct Node* newNode(int data)
{
    struct Node* temp = new Node;
    temp->val = data;
    temp->left = temp->right = NULL;
    return temp;
}
  
// cur for storing the current count of the value
// and mx for the maximum count of the element which is denoted by node
  
int cur = 1, mx = 0;
int node;
struct Node* previous = NULL;
  
// Find the inorder traversal of the BST
void inorder(struct Node* root)
{
    // If root is NULL then return
    if (root == NULL) {
        return;
    }
    inorder(root->left);
    if (previous != NULL) {
        // If the previous value is equal to the current value
        // then increase the count
        if (root->val == previous->val) {
            cur++;
        }
        // Else initialize the count by 1
        else {
            cur = 1;
        }
    }
    // If currrent count is greater than the max count
    // then update the mx value
    if (cur > mx) {
        mx = cur;
        node = root->val;
    }
    // Make the current Node as previous
    previous = root;
    inorder(root->right);
}
  
// Utility function
int findnode(struct Node* root)
{
    inorder(root);
    return node;
}
int main()
{
    /* Let us create following BST
                   6
                 /    \
                5       7
              /   \    /  \
             4     5  7    7 
    */
  
    struct Node* root = newNode(6);
    root->left = newNode(5);
    root->right = newNode(7);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(7);
    root->right->right = newNode(7);
  
    cout << "Node of BST is " << findnode(root) << '\n';
    return 0;
}


Java
/* Java program to find the median of BST 
in O(n) time and O(1) space*/
class GFG
{
      
/* A binary search tree Node has data, pointer
to left child and a pointer to right child */
static class Node
{
    int val;
    Node left, right;
};
  
static Node newNode(int data)
{
    Node temp = new Node();
    temp.val = data;
    temp.left = temp.right = null;
    return temp;
}
  
// cur for storing the current count 
// of the value and mx for the maximum count
// of the element which is denoted by node
static int cur = 1, mx = 0;
static int node;
static Node previous = null;
  
// Find the inorder traversal of the BST
static void inorder(Node root)
{
    // If root is null then return
    if (root == null) 
    {
        return;
    }
    inorder(root.left);
    if (previous != null) 
    {
          
        // If the previous value is equal to 
        // the current value then increase the count
        if (root.val == previous.val) 
        {
            cur++;
        }
          
        // Else initialize the count by 1
        else 
        {
            cur = 1;
        }
    }
      
    // If currrent count is greater than the 
    // max count then update the mx value
    if (cur > mx) 
    {
        mx = cur;
        node = root.val;
    }
      
    // Make the current Node as previous
    previous = root;
    inorder(root.right);
}
  
// Utility function
static int findnode(Node root)
{
    inorder(root);
    return node;
}
  
// Java Code
public static void main(String args[])
{
    /* Let us create following BST
                6
                / \
                5     7
            / \ / \
            4     5 7 7 
    */
    Node root = newNode(6);
    root.left = newNode(5);
    root.right = newNode(7);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.left = newNode(7);
    root.right.right = newNode(7);
  
    System.out.println("Node of BST is " + 
                          findnode(root));
}
}
  
// This code is contributed by Arnab Kundu


Python3
# Python program to find the median of BST
# in O(n) time and O(1) space
  
# A binary search tree Node has data, pointer
# to left child and a pointer to right child
class Node:
    def __init__(self):
        self.val = 0
        self.left = None
        self.right = None
  
def newNode(data: int) -> Node:
    temp = Node()
    temp.val = data
    temp.left = temp.right = None
    return temp
  
# cur for storing the current count
# of the value and mx for the maximum count
# of the element which is denoted by node
cur = 1
mx = 0
node = 0
previous = Node()
  
# Find the inorder traversal of the BST
def inorder(root: Node):
    global cur, mx, node, previous
  
    # If root is null then return
    if root is None:
        return
  
    inorder(root.left)
  
    if previous is not None:
  
        # If the previous value is equal to
        # the current value then increase the count
        if root.val == previous.val:
            cur += 1
  
        # Else initialize the count by 1
        else:
            cur = 1
  
    # If currrent count is greater than the
    # max count then update the mx value
    if cur > mx:
        mx = cur
        node = root.val
  
    # Make the current Node as previous
    previous = root
    inorder(root.right)
  
# Utility function
def findNode(root: Node) -> int:
    global node
  
    inorder(root)
    return node
  
# Driver Code
if __name__ == "__main__":
    # Let us create following BST
    #         6
    #         / \
    #     5     7
    #     / \ / \
    #     4 5 7 7
    root = newNode(6)
    root.left = newNode(5)
    root.right = newNode(7)
    root.left.left = newNode(4)
    root.left.right = newNode(5)
    root.right.left = newNode(7)
    root.right.right = newNode(7)
  
    print("Node of BST is", findNode(root))
  
# This code is contributed by
# sanjeev2552


C#
/* C# program to find the median of BST 
in O(n) time and O(1) space*/
using System;
      
class GFG
{
      
/* A binary search tree Node has data, pointer
to left child and a pointer to right child */
public class Node
{
    public int val;
    public Node left, right;
};
  
static Node newNode(int data)
{
    Node temp = new Node();
    temp.val = data;
    temp.left = temp.right = null;
    return temp;
}
  
// cur for storing the current count 
// of the value and mx for the maximum count
// of the element which is denoted by node
static int cur = 1, mx = 0;
static int node;
static Node previous = null;
  
// Find the inorder traversal of the BST
static void inorder(Node root)
{
    // If root is null then return
    if (root == null) 
    {
        return;
    }
    inorder(root.left);
    if (previous != null) 
    {
          
        // If the previous value is equal to 
        // the current value then increase the count
        if (root.val == previous.val) 
        {
            cur++;
        }
          
        // Else initialize the count by 1
        else
        {
            cur = 1;
        }
    }
      
    // If currrent count is greater than the 
    // max count then update the mx value
    if (cur > mx) 
    {
        mx = cur;
        node = root.val;
    }
      
    // Make the current Node as previous
    previous = root;
    inorder(root.right);
}
  
// Utility function
static int findnode(Node root)
{
    inorder(root);
    return node;
}
  
// Driver Code
public static void Main(String []args)
{
    /* Let us create following BST
                6
                / \
                5     7
            / \ / \
            4     5 7 7 
    */
    Node root = newNode(6);
    root.left = newNode(5);
    root.right = newNode(7);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.left = newNode(7);
    root.right.right = newNode(7);
  
    Console.WriteLine("Node of BST is " + 
                         findnode(root));
}
}
  
// This code is contributed by PrinciRaj1992


输出:
node of BST is 7

时间复杂度:  O(N)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。