leetcode501. 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.java

Assume a BST is defined as follows:node

  • 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],less

1
    \
     2
    /
   2

return [2].spa

Note: If a tree has more than one mode, you can return them in any order.code

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).ci

现有一个能够包含重复元素的二叉查找树,该二叉查找树知足全部左节点的值均小于等于父节点,全部右节点均大于等于父节点。现要求找出全部出现次数最多的值。element

思路和代码

题目中有一个额外的要求,就是只用O(1)的空间复杂度来完成此次计算。这里就复述一下在回答里面一个很是很是棒的解答。即经过两次中序遍从来完成。第一次中序遍历将计算出出现最多的次数。第二次中序遍历则将统计的次数等于第一次计算出的最屡次数的结果相等的值加入结果集中。it

int maxCount;
    int curCount;
    int curValue;
    int[] result;
    int modeCount;

    public int[] findMode(TreeNode root) {
        inorder(root);
        result = new int[modeCount];
        curCount = 0;
        modeCount = 0;
        inorder(root);
        return result;
    }

    private void inorder(TreeNode node) {
        if (node == null) {
            return;
        }
        inorder(node.left);
        handle(node.val);
        inorder(node.right);
    }

    private void handle(int val) {
        if (val != curValue) {
            curCount = 0;
            curValue = val;
        }
        curCount++;
        if (curCount > maxCount) {
            modeCount = 1;
            maxCount = curCount;
        }else if (curCount == maxCount) {
            if (result != null) {
                result[modeCount] = curValue;
            }
            modeCount++;
        }
    }
相关文章
相关标签/搜索