国产探花免费观看_亚洲丰满少妇自慰呻吟_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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西峡县| 盖州市| 涞水县| 开阳县| 西青区| 邻水| 根河市| 眉山市| 万荣县| 林州市| 遂溪县| 义乌市| 江源县| 拉孜县| 青阳县| 武陟县| 海阳市| 三河市| 达孜县| 庆云县| 永和县| 剑川县| 阜宁县| 渭南市| 昆山市| 庆云县| 宁河县| 昌平区| 浙江省| 博白县| 枣强县| 台南县| 巴林左旗| 迁西县| 固原市| 溆浦县| 道真| 濉溪县| 宁强县| 千阳县| 木兰县|