天天看點

【leetcode刷題】T136-二叉搜尋樹中的衆數

木又連續日更第92天(92/100)

木又的第136篇leetcode解題報告

二叉樹

類型第26篇解題報告

leetcode第501題:二叉搜尋樹中的衆數

https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/

【題目】

給定一個有相同值的二叉搜尋樹(BST),找出 BST 中的所有衆數(出現頻率最高的元素)。

假定 BST 有如下定義:

結點左子樹中所含結點的值小于等于目前結點的值

結點右子樹中所含結點的值大于等于目前結點的值

左子樹和右子樹都是二叉搜尋樹

例如:
給定 BST [1,null,2,2],
   1
    \
     2
    /
   2
傳回[2].
           

複制

提示:如果衆數超過1個,不需考慮輸出順序

進階:你可以不使用額外的空間嗎?(假設由遞歸産生的隐式調用棧的開銷不被計算在内)

【思路】

最簡單的想法:遞歸周遊二叉樹,使用字典儲存所有值及其出現次數,最後找到字典中最大出現次數及其對應值。

【代碼】

python版本

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        self.d = {}
        self.count(root)
        max_val = max(self.d.values())
        return list(map(lambda x: x[0], filter(lambda x: x[1] == max_val, self.d.items())))

    def count(self, node):
        if not node:
            return 
        self.d[node.val] = self.d.get(node.val, 0) + 1
        self.count(node.left)
        self.count(node.right)
           

複制

C++版本

/**
 * 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> findMode(TreeNode* root) {
        vector<int> res;
        if(!root)
            return res;
        map<int, int> d;
        count(root, d);

        int max_val = d[root->val];
        map<int, int>:: iterator it;
        for(it=d.begin(); it != d.end(); it++){
            if(it->second > max_val){
                max_val = it->second;
                res.erase(res.begin(), res.end());
                res.push_back(it->first);
            }else{
                if(it->second == max_val)
                    res.push_back(it->first);
            }
        }
        return res;
    }

    void count(TreeNode* node, map<int, int>& d){
        if(!node)
            return;
        d[node->val]++;
        count(node->left, d);
        count(node->right, d);
    }
};
           

複制