zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    ABAP-FI-Redirection of read accesses from ANEA to FAAV_ANEA failed
    招聘
    五分钟教你在长沙如何找到靠谱的驾校和教练(长沙找驾校)
    数组哪些方法能改变原数组,以及循环改变数组的情况
    FXGL游戏开发-JavaFX游戏框架
    tempermonkey.d.ts | 油猴函数类型
    post导出文件
    mescroll.js 使用
    查看托管应用池用法
    IDEA配置
  • 原文地址:https://www.cnblogs.com/immjc/p/7554403.html
Copyright © 2011-2022 走看看