> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/binary-search-tree/find-mode-in-binary-search-tree.md).

# Find Mode in Binary Search Tree

## Find Mode in Binary Search Tree

<https://leetcode.com/problems/find-mode-in-binary-search-tree/description/>

> Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

## Thoughts

看到BST想到它的性质用中序遍历会得到排好序的结点，然后我们就可以数相同元素有几个了。\
为了节省空间, 可以用两次中序遍历存储maxLen.

## Code

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private void pushLeft(Stack<TreeNode> stack, TreeNode node) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
    }

    public int[] findMode(TreeNode root) {
        TreeNode last = null;
        int max = 0, seqLen = 0, maxCount = 0;
        Stack<TreeNode> stack = new Stack<>();
        pushLeft(stack, root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (last != null && node.val == last.val) {
                seqLen++;
            } else {
                seqLen = 1;
            }
            if (seqLen == max) {
                maxCount++;
            } else if (seqLen > max) {
                maxCount = 1;
                max = seqLen;
            }
            last = node;
            pushLeft(stack, node.right);
        }
        last = null;
        int[] res = new int[maxCount];
        pushLeft(stack, root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (last != null && node.val == last.val) {
                seqLen++;
            } else {
                seqLen = 1;
            }
            if (seqLen == max) {
                res[--maxCount] = node.val;
            }
            last = node;
            pushLeft(stack, node.right);
        }
        return res;
    }
}
```

### Analysis

Errors:\
1\. 老版本调用两次inOder时第二次忘了把last设成null\
1\. seqLen >= maxLen就清空了res, 导致前面的==max的被删掉

时间复杂度为中序遍历O(n).
