?LeetCode刷題實(shí)戰(zhàn)501:二叉搜索樹中的眾數(shù)
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
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.
示例? ? ? ? ? ? ? ? ? ? ? ? ?

解題
class?Solution?{
????// 記錄前一個(gè)指針
????private?TreeNode pre = null;
????// 計(jì)算出現(xiàn)次數(shù)
????private?int?count = 0;
????// 最大的出現(xiàn)頻率
????private?int?maxCount = 0;
????private?Listlist = new?ArrayList<>();
????public?int[] findMode(TreeNode root) {
????????searchBST(root);
????????int[] ans = new?int[list.size()];
????????for?(int?i = 0; i < ans.length; i++) {
????????????ans[i] = list.get(i);
????????}
????????return?ans;
????}
????private?void?searchBST(TreeNode cur) {
????????if?(cur == null) return;
????????searchBST(cur.left);
????????if?(pre == null) {
????????????count = 1;
????????} else?if?(pre.val == cur.val) {
????????????count++;
????????} else?if?(pre.val != cur.val) {
????????????count = 1;
????????}
????????pre = cur;
????????if?(count == maxCount) {
????????????list.add(cur.val);
????????}
????????if?(count > maxCount) {
????????????maxCount = count;// 更新最大的頻率
????????????list.clear(); // 清空列表,之前的元素失效
????????????list.add(cur.val);
????????}
????????searchBST(cur.right);
????}
}
