国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

501. Find Mode in Binary Search Tree

2019-11-08 03:21:28
字體:
來源:轉載
供稿:網友

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). 渣方法

/** * 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: map<int, int> ans; void dfs(TreeNode* node){ if(node == NULL) return; ans[node->val]++; dfs(node->left); dfs(node->right); } vector<int> findMode(TreeNode* root) { dfs(root); vector<int> v; int max = -1; for(auto itr = ans.begin(); itr != ans.end(); ++itr){ if(itr->second > max){ max = itr->second; v.clear(); v.push_back(itr->first); } else if(itr->second == max){ v.push_back(itr->first); } } return v; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 威海市| 九龙坡区| 博湖县| 海伦市| 图片| 兴山县| 普格县| 锡林浩特市| 湟中县| 永和县| 台州市| 东宁县| 长治市| 青河县| 宾阳县| 周宁县| 延寿县| 察隅县| 泰安市| 扎囊县| 巢湖市| 台东县| 田东县| 承德市| 建始县| 图木舒克市| 尚志市| 宜兴市| 石首市| 遵义市| 鲜城| 榆中县| 伊宁市| 秦皇岛市| 永泰县| 南陵县| 平定县| 皋兰县| 汉寿县| 个旧市| 鹤壁市|