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++;
        }
    }
相關文章
相關標籤/搜索