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.

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++;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章