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:

  1. The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  2. The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  3. 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).

Tips: Time: O(n) Space: extra O(1) 利用BST的特性,recursive中序遍历然后找众数。注意list.clear();

Code:

public class Solution {
    int curCount = 1;
    int maxCount = 0;
    TreeNode prev;
    public int[] findMode(TreeNode root) {
        if (root == null) return new int[0];
        List<Integer> list = new ArrayList<>();
        inorder(root, list);
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) res[i] = list.get(i);
        return res;
    }
    private void inorder(TreeNode root, List<Integer> list) {
        if (root == null) return;
        inorder(root.left, list);
        if (prev != null) {
            if (root.val == prev.val) curCount++;
            else curCount = 1;
        }
        prev = new TreeNode(root.val);
        if (curCount > maxCount) {
            maxCount = curCount;
            list.clear();
            list.add(root.val);
        } else if (curCount == maxCount) list.add(root.val);
        inorder(root.right, list);
    }
}

results matching ""

    No results matching ""