501. Find Mode in Binary Search Tree
in Find Tree search Binary mode
2023-09-11 14:14:21 时间
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).
private readonly Dictionary<int, int> dictionary = new Dictionary<int, int>(); public int[] FindMode(TreeNode root) { Chuck(root); if (dictionary.Count > 0) { int max = dictionary.Max(x => x.Value); var array = dictionary.Where(x => x.Value == max).Select(x => x.Key).ToArray(); return array; } else { return new int[0]; } } private void Chuck(TreeNode node) { if (node == null) { return; } int val = node.val; if (dictionary.ContainsKey(val)) { dictionary[val]++; } else { dictionary[val] = 1; } Chuck(node.left); Chuck(node.right); }
Runtime: 272 ms, faster than 32.05% of C# online submissions for Find Mode in Binary Search Tree.
Memory Usage: 33.1 MB, less than 11.30% of C# online submissions forFind Mode in Binary Search Tree.
相关文章
- 【Maven异常】Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/maven/cli/MavenCli : Unsupported major.minor version 51.0
- MySQL比like语句更高效的写法locate position instr find_in_set
- 【MySQL】FIND_IN_SET、LIKE、IN的区别
- [Python] Read from a File in Python
- [XState] Invoking a Promise for Asynchronous State Transitions in XState
- [Vue-rx] Share RxJS Streams to Avoid Multiple Requests in Vue.js
- [Typescript] Key remapping in mapped types by using `as` keyword V4.2
- [Angular] Use Angular components in AngularJS applications with Angular Elements
- [Bash] Find Files and Folders with `find` in Bash
- [Angular] Create a custom validator for reactive forms in Angular
- [NPM] Test npm packages locally in another project using npm link
- [LeetCode] Find Minimum in Rotated Sorted Array II
- 【RF库Collections测试】Count Values In List
- could not find any translatable text for key 'Search' in bundle '/cus.crm.notes/
- Cannot find source code based button in SE24
- different color in Chrome Development Tool
- Find problem in eXtremeDB
- leetcode之Find All Numbers Disappeared in an Array
- Spark SQL 源代码分析之 In-Memory Columnar Storage 之 in-memory query
- Network Service in Chrome
- 论文阅读《Extracting Multiple-Relations in One-Pass with Pre-Trained Transformers》
- Error response from daemon: removal of container XXX is already in progress