[LeetCode] 501. Find Mode in Binary Search Tree

来源:互联网 发布:克里斯.邓恩数据 编辑:程序博客网 时间:2024/06/04 18:54
Given a binary search tree (BST) with duplicates, find all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (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).
class Solution {public:    vector<int> findMode(TreeNode* root) {        vector<int> tracking;        InOrder(root, tracking);        vector<int> res;        int MaxCount = 0;        auto it = tracking.begin();        while (it != tracking.end()) {            auto range = equal_range(it, tracking.end(), *it);            auto Count = range.second - range.first;            if (Count >= MaxCount) {                if (Count > MaxCount) {                    res.clear();                    MaxCount = Count;                }                res.push_back(*it);            }            it = range.second;        }        return res;    }private:    void InOrder(TreeNode *root, vector<int> &tracking) {        if (root == nullptr) return;        InOrder(root->left, tracking);        tracking.push_back(root->val);        InOrder(root->right, tracking);    }};

这里写图片描述

阅读全文
0 0
原创粉丝点击