Monday, September 26, 2022

[LeetCode] Find Mode in Binary Search Tree

Problem: Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

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.

Example:

Input: root = [1,null,2,2]
Output: [2]


Approach: A simple inorder traversal can work here as in case of BST, inorder traversal will give the output in sorted order. Just look at the implementation to understand it.


Implementation in C#:

    public int[] FindMode(TreeNode root) 

    {

        if (root == null)

        {

            return null;

        }      

        int max = 0;

        TreeNode prevNode = null;

        int prevFreq = 0;

        List<int> result = new List<int>();   

        this.FindModeInorder(root, ref prevNode, ref prevFreq, result, ref max);

        return result.ToArray();

    }

    

    private void FindModeInorder(TreeNode node,

                                ref TreeNode prevNode,

                                ref int prevFreq,

                                List<int> result,

                                ref int max)

    {

        if (node == null)

        {

            return;

        }

        this.FindModeInorder(node.left, ref prevNode, ref prevFreq, result, ref max);

        if (prevNode != null)

        {

            if (node.val == prevNode.val)

            {

                ++prevFreq;

            }

            else

            {

                prevFreq = 1;

            }

        }

        else

        {

            // Current node is the leftmost node

            ++prevFreq;

            max = prevFreq;

        }

        prevNode = node;

        if (prevFreq > max)

        {

            max = prevFreq;

            result.Clear();

            result.Add(node.val);

        }

        else if(prevFreq == max)

        {

            result.Add(node.val);

        }

        this.FindModeInorder(node.right, ref prevNode, ref prevFreq, result, ref max);

    }


Complexity: O(n)

No comments:

Post a Comment