[LeetCode] Find Mode in Binary Search Tree

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Find Mode in Binary Search Tree相关的知识,希望对你有一定的参考价值。

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

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.

For example:
Given BST [1,null,2,2],

   1
         2
    /
   2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

找出二叉搜索树中最常见的元素。因为题目要求是严格的二叉搜索树。想了一个简单但是效率很低的方法。

首先中序遍历二叉搜索树存入一个数组中,然后将数组元素放去map统计出现的最大次数。最后在遍历一个map把最常见的元素放去结果数组中。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorder;
    vector<int> findMode(TreeNode* root) {
        unordered_map<int, int> m;
        vector<int> res;
        dfs(root);
        int cnt = 0;
        for (auto n : inorder)
            m[n]++;
        for (auto it = m.begin(); it != m.end(); it++) {
            if (it->second > cnt)
                cnt = it->second;
        }
        for (auto it = m.begin(); it != m.end(); it++) {
            if (it->second == cnt) {
                res.push_back(it->first);
            }
        }
        return res;
    }
    
    vector<int> dfs(TreeNode* root) {
        if (root == nullptr)
            return inorder;
        dfs(root->left);
        inorder.push_back(root->val);
        dfs(root->right);
        return inorder;
    }
};
// 59 ms

 


以上是关于[LeetCode] Find Mode in Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode_501. Find Mode in Binary Search Tree

[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree

leetcode501. Find Mode in Binary Search Tree

[LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数

LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)

LeetCode算法题-Find Mode in Binary Search Tree(Java实现)