查找二叉树中出现次数最多的数 Find Mode in Binary Search Tree

问题:node

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.less

Assume a BST is defined as follows:spa

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

    1
    \
     2
    /
   2

return [2].递归

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

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

① 利用一个哈希表来记录数字和其出现次数之间的映射,而后维护一个变量max来记录当前最多的次数值,这样在遍历完树以后,根据这个max值就能把对应的元素找出来。使用中序遍历方式递归遍历该树(注:使用任何一种遍历方式均可以 )。时间和空间复杂度都是O(N)get

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution { // 16ms
    private int max = 0;//由于在两个方法中都使用到了这两个变量,因此将其声明在方法外面。
    private Map<Integer,Integer> map = new HashMap<>();

    public int[] findMode(TreeNode root) {
        if (root == null) return new int[0];
        List<Integer> list = new ArrayList<>();
        inorder(root);
        for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
            if(entry.getValue() == max) list.add(entry.getKey());
        }
        int[] res = new int[list.size()];
        for (int i = 0;i < list.size() ;i ++ ) {
            res[i] = list.get(i);
        }
        return res;
    }
    public void inorder(TreeNode node){
        if(node == null) return;
        if(node.left != null)inorder(node.left);
        map.put(node.val,map.getOrDefault(node.val,0) + 1);
        max = Math.max(max,map.get(node.val));
        if(node.right != null)inorder(node.right);
    }
}it

② 中序遍历获得一个递增的序列,使用一个计数器count记录相同的值的个数,max记录最大个数,pre记录前一个节点的值用于判断当前节点与前一个是否相等,从而决定要如何操做count;时间复杂度O(n),空间复杂度O(1)

public class Solution { //5 ms
    int pre = Integer.MIN_VALUE;//记录前一个节点数值,用于比较当前节点与以前的节点是否相等
    int count = 0;
    int max = 0;

    public int[] findMode(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inorder(root, list);//中序遍历
        int[] arr = new int[list.size()];
        for(int i = 0;i < arr.length;i ++){
                arr[i] = list.get(i);
        }
        return arr;
    }
    public void inorder(TreeNode root, List<Integer> list){
        if(root != null){
            inorder(root.left, list);
            if(root.val == pre){                 count ++;                             }else{                 count = 1;                 pre = root.val;             }             if(count > max){                 max = count;                 list.clear();                 list.add(root.val);             }else if(count == max){                 list.add(root.val);             }             inorder(root.right, list);         }     } }

相关文章
相关标签/搜索