LeetCode-501. Find Mode in Binary Search Tree(Java)
来源:互联网 发布:淘宝玻璃钢化粪罐 编辑:程序博客网 时间:2024/06/08 09:22
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]
.
题意
从一个二叉搜索树中找到出现最频繁的元素,即出现次数最多的元素。
思路
采用三个遍历方式之一;因为要记录相同元素出现的次数,所以需要记录上一个节点用来判断,如果上一个节点与当前节点相同,
则出现次数加1,否则,出现次数重置,当前节点赋值给上一个节点;同时记录大于等于出现最大次数的元素,所以需要一个数组,
然后需要一个计数器,当如果上一个节点与当前节点不相同时并且当前节点出现次数大于或等于最大出现次数,把该节点值添加到数组,
并且该计数器加1。大致思路如此
代码
public class Solution { public int[] findMode(TreeNode root) { inorder(root); modes = new int[modeCount]; modeCount = 0; currCount = 0; inorder(root); return modes; } //记录元素值 private int currVal; //记录相同元素出现次数 private int currCount = 0; //记录出现的最大次数 private int maxCount = 0; //作为modes数组的下标,记录出现相同最大次数的元素个数 private int modeCount = 0; private int[] modes; private void handleValue(int val) { if (val != currVal) { currVal = val; currCount = 0; } currCount++; if (currCount > maxCount) { maxCount = currCount; modeCount = 1; } else if (currCount == maxCount) { if (modes != null) modes[modeCount] = currVal; modeCount++; } } private void inorder(TreeNode root) { if (root == null) return; inorder(root.left); handleValue(root.val); inorder(root.right); }}
参考链接:https://discuss.leetcode.com
阅读全文
0 0
- LeetCode-501. Find Mode in Binary Search Tree(Java)
- [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
- leetcode 501. Find Mode in Binary Search Tree
- [Leetcode] 501. Find Mode in Binary Search Tree 解题报告
- 欢迎使用CSDN-markdown编辑器
- Bagging和Boosting 概念及区别
- 确保非局部静态对象使用前被初始化
- scala中_的作用
- 实现 AlertDialog 点击确定按钮不关闭
- LeetCode-501. Find Mode in Binary Search Tree(Java)
- D. Lakes in Berland
- 30分钟搭建Java后端开发环境
- 表的垂直拆分和水平拆分
- 最大公约数与最小公倍数(gcd,lcm)
- Original error: Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1
- linux命令---pidstat
- 【loj】#6006. 「网络流 24 题」试题库(二分图匹配)
- web中 checkbox的全选