LeetCode 501. Find Mode in Binary Search Tree

Inequality-Sign發表於2018-03-20

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).
查詢出二叉搜尋樹中所有重複數量最多的值

這個題也花了我不少時間

由於是二叉搜尋樹,所以如果通過中序遍歷遍歷出來的值肯定是連續的,所以只要知道之前遍歷節點值得個數和最大重複數量就可以了。問題在於遞迴回溯的時候要得到前一個的記錄,那麼要麼傳引用,要麼只能用全域性變數。無奈java傳不了引用,最大值max只能通過max[0]來傳遞了,但是前一個節點的引用實在沒法了,只能用個全域性了。突然懷念以前c++一個&就能方便的解決這些傳遞問題了

程式碼如下,有些冗長,以後優化

 public int[] findMode(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        int[] count = new int[]{0};
        int[] max = new int[]{1};
        findMode(list,  root, count, max);
        int[] re = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            re[i] = list.get(i);
        }
        return re;
    }

    private TreeNode preNode = null;

    public void findMode(List<Integer> list,TreeNode curNode, int[] count, int[] max) {

        if(curNode == null) return;
        findMode(list, curNode.left, count, max);
        if (preNode == null) {
            count[0]++;
            preNode = curNode;

        }
        else if (curNode.val == preNode.val) {
            count[0]++;
        } else {
            count[0] = 1;
        }

        if (count[0] > max[0]) {
            list.clear();
            max[0] = count[0];
            list.add(curNode.val);
        }
        else if (count[0] == max[0]) {
            list.add(curNode.val);
        }
        preNode = curNode;
        findMode(list, curNode.right, count, max);
    }

相關文章