leetcode501-Find-Mode-in-Binary-Search-Tree

49次阅读

共计 1298 个字符,预计需要花费 4 分钟才能阅读完成。

题目要求

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).

现有一个可以包含重复元素的二叉查找树,该二叉查找树满足所有左节点的值均小于等于父节点,所有右节点均大于等于父节点。现要求找出所有出现次数最多的值。

思路和代码

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

    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++;
        }
    }

正文完
 0