package com.app.main.LeetCode.tree;
import com.app.main.LeetCode.base.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
*
* 501
*
* easy
*
* https://leetcode.com/problems/find-mode-in-binary-search-tree/
*
* 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).
*
*
*
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/11/15
* Time:下午8:53
*/
public class FindModeInBinarySearchTree {
private TreeNode pre = null;
private Integer max = 0;
private Integer cn = 0;
// mode 众数
public int[] findMode(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorderTraversal(root, result);
int[] res = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
res[i] = result.get(i);
}
return res;
}
private void inorderTraversal(TreeNode curr, List<Integer> result) {
if (curr != null) {
if (curr.left != null) {
inorderTraversal(curr.left, result);
}
// todo
if (pre != null) {
if (curr.val == pre.val) {
cn++;
if (cn == max) {
result.add(curr.val);
} else if (cn > max) {
result.clear();
result.add(curr.val);
max = cn;
}
} else {
cn = 1;
if (cn == max) {
result.add(curr.val);
}
}
pre = curr;
} else {
// init
pre = curr;
cn = 1;
max = 1;
result.add(curr.val);
}
if (curr.right != null) {
inorderTraversal(curr.right, result);
}
}
}
}