博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
501. Find Mode in Binary Search Tree
阅读量:4258 次
发布时间:2019-05-26

本文共 1538 字,大约阅读时间需要 5 分钟。

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).

题目要求找出出现最多的元素多代表的mode,即可能有多个元素出现了相同最多次;

但是要求不能使用额外的内存资源,除了递归时栈调用所使用的资源。
可以使用二叉排序树的中序遍历方法,遍历找出出现次数最多的元素。

class Solution {private:    vector
res; int curval, maxcount = 0, tempcount = 0;public: void dfs_findMode(TreeNode *root){ if (root == NULL)return; dfs_findMode(root->left); tempcount++; if (root->val != curval){ curval = root->val; tempcount = 1; } if (tempcount > maxcount){ maxcount = tempcount; res.clear(); res.push_back(root->val); } else if (tempcount == maxcount){ res.push_back(root->val); } dfs_findMode(root->right); } vector
findMode(TreeNode* root) { if (root == NULL)return vector
{}; dfs_findMode(root); return res; }};

转载地址:http://eixei.baihongyu.com/

你可能感兴趣的文章
C/C++输入输出
查看>>
泸州NGN属南气矿工程----华为s2600磁盘阵列问题解决
查看>>
泸州属南气矿----配置S2600磁盘阵列报错:There is no master controller.
查看>>
SQL 调优1
查看>>
OA报账规范(出差专用)
查看>>
生产库快速关闭数据库
查看>>
差异增量备份和累积增量备份的差别
查看>>
ASM 无法发现候选磁盘组----grid 11.2.0.3 asm 自检通不过 prvf-5184
查看>>
ASM 无法发现候选磁盘组----丢失的ASM磁盘组 ASM的磁盘组无法挂载
查看>>
Oracle 10g配置单向stream流复制,完整记录
查看>>
ORA-00845 MEMORY_TARGET not supported on this system
查看>>
ORA-00257: archiver error --11GR2 RAC 设置归档路径和开启flashback
查看>>
奕新集团项目--Oracle 源RAC ---目标 RAC GG 搭建 11.2.3 版本 双向同步
查看>>
What is SCAN in Oracle 11g R2 RAC
查看>>
关于Recycle Bin是什么以及实验
查看>>
Linux搭建时间同步服务器
查看>>
ORA-12541: TNS:no listener
查看>>
mysql数据库存储路径更改 数据文件位置
查看>>
Could not fetch specs from https://rubygems.org/
查看>>
oracle日志分析工具LogMiner使用
查看>>