[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 / 2return `[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
- [Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
- LeetCode 501. Find Mode in Binary Search Tree
- leetcode 501. Find Mode in Binary Search Tree
- LeetCode-501. Find Mode in Binary Search Tree
- Leetcode——501. Find Mode in Binary Search Tree
- LeetCode 501.Find Mode in Binary Search Tree
- LeetCode 501. Find Mode in Binary Search Tree
- [LeetCode] 501. Find Mode in Binary Search Tree 解题报告
- [LeetCode]501. Find Mode in Binary Search Tree
- [leetcode: Python]501. Find Mode in Binary Search Tree
- [leetcode]: 501. Find Mode in Binary Search Tree
- leetcode 501. Find Mode in Binary Search Tree
- [LeetCode] 501. Find Mode in Binary Search Tree
- [leetcode]501. Find Mode in Binary Search Tree
- LeetCode-501. Find Mode in Binary Search Tree(Java)
- leetcode 501. Find Mode in Binary Search Tree
- leetcode 501. Find Mode in Binary Search Tree
- [Leetcode] 501. Find Mode in Binary Search Tree 解题报告
- MySql优化原理
- java多线程系列--“基础篇”01之 基本概念
- iOS开发设置statusBar样式
- 欢迎使用CSDN-markdown编辑器
- PHP闭包 function() use()
- [LeetCode] 501. Find Mode in Binary Search Tree
- Linux strace工具,进程诊断、排错、跟踪系统调用和信号量
- c++11 你需要知道这些就够了
- Mac opencv 3.0 + python 3.6 安装踩坑全记录,总有一个坑是你要踩的
- protobuf反射详解
- 浅谈Java中BIO、NIO、AIO的概念
- android 中遇到的异常汇总
- Touchable示例
- 解决阿里云服务器只能内网访问,外网访问不了