码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Find Mode in Binary Search Tree

时间:2017-09-19 22:59:48      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:tar   中序   color   res   must   tor   ptr   extra   tps   

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

标签:tar   中序   color   res   must   tor   ptr   extra   tps   

原文地址:http://www.cnblogs.com/immjc/p/7554403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!