查找二叉树中出现次数最多的数 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).

解决:

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

/**
 * 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);
    }
}

② 中序遍历得到一个递增的序列,使用一个计数器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);
        }
    }
}

 

转载于:https://my.oschina.net/liyurong/blog/1505273

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值