Header Ad

Leetcode Find Mode in Binary Search Tree problem solution

In this Leetcode Find Mode in Binary Search Tree problem solution 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.

Leetcode Find Mode in Binary Search Tree problem solution


Problem solution in Python.

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        self.res, self.maxcount, self.curcount, self.curnum = [], 0, 0, float("-Inf")
        
        def helper(node):
            if node: 
                helper(node.left)
                if self.curnum != node.val:
                    self.curnum = node.val
                    self.curcount = 1 
                else: 
                    self.curcount += 1
                if self.curcount == self.maxcount: 
                    self.res.append(node.val)
                elif self.curcount > self.maxcount:
                    self.maxcount = self.curcount 
                    self.res = [node.val]
                helper(node.right)
        
        helper(root)
        return self.res

Problem solution in Java.

public int[] findMode(TreeNode root) {
        List<Integer> modes = new LinkedList<>();
        if(root == null) return new int[]{};
        findMode(root, modes);
        int[] res = new int[modes.size()];
        int i=0;
        for(int m : modes) res[i++] = m;
        return res;
    }
    int maxCount = 1, count = 1;
    Integer prev = null; 
    private void findMode(TreeNode root, List<Integer> modes){
        if(root == null) return;
        findMode(root.left, modes);
        if(prev != null && prev == root.val)
            ++count;
        else
            count = 1;
        if(maxCount <= count){
            if(maxCount < count)
                modes.clear();
            modes.add(root.val);
            maxCount = count;
        }
        prev = root.val;
        findMode(root.right, modes);
    }


Problem solution in C++.

class Solution {
public:
    unordered_map<int,int>mp;
    int max=0;
    
    void dfs(TreeNode* root){
        if(root==NULL)return;
        mp[root->val]++;
        if(max<mp[root->val])max=mp[root->val];
        dfs(root->left);
        dfs(root->right);
    }
    
    vector<int> findMode(TreeNode* root) {
        vector<int>v;
        if(root==NULL)return v;
        dfs(root);
        for(auto i:mp){
            if(i.second==max)v.push_back(i.first);
        }return v;
    }
};


Post a Comment

0 Comments