LeetCode501
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
class Solution {TreeNode pre = null;LinkedList<Integer> list = new LinkedList<>();int maxCount = 0;int count = 0;public int[] findMode(TreeNode root) {if (root == null) {return new int[]{};}preOrder(root);int size = list.size();int[] arr = new int[size];for (int i = 0; i < size; i++) {arr[i] = list.get(i);}return arr;}private void preOrder(TreeNode root) {if (root == null) {return;}if (root.left != null) {preOrder(root.left);}if (pre == null) {count = 1;} else if (pre.val == root.val) {count++;} else {count = 1;}pre = root;if (count == maxCount){list.addLast(root.val);}if (count > maxCount) {list.clear();maxCount = count;list.addLast(root.val);}if (root.right != null) {preOrder(root.right);}}}
