• LeetCode算法题-Find Mode in Binary Search Tree(Java实现)


    这是悦乐书的第246次更新,第259篇原创

    01 看题和准备

    今天介绍的是LeetCode算法题中Easy级别的第113题(顺位题号是501)。给定具有重复项的二叉搜索树(BST),找到给定BST中的所有模式(最常出现的元素)。假设BST定义如下:

    节点的左子树仅包含键小于或等于节点键的节点。

    节点的右子树仅包含键大于或等于节点键的节点。

    左右子树也必须是二叉搜索树。

    例如:

    鉴于BST [1,null,2,2],

       1
        
         2
        /
       2
    

    返回[2]。

    注意:如果树有多个模式,您可以按任何顺序返回它们。

    跟进:你可以不使用任何额外的空间吗? (假设由于递归而产生的隐式堆栈空间不计算)。

    本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

    02 第一种解法

    使用一个max变量来表示二叉树中的出现次数最多的节点值,使用HashMap来存储每个节点值及其出现的次数,借助一个递归方法,对二叉树中的节点值进行遍历,每次都将max的值进行更新。在遍历完所有节点后,先将最大值添加进ArrayList中,最后再以整型数组作为结果返回。

    private Map<Integer, Integer> map;
    private int max = 0;
    public int[] findMode(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        map = new HashMap<Integer, Integer>();
        findMax(root);
        List<Integer> list = new LinkedList<>();
        for (int key: map.keySet()) {
            if (map.get(key) == max) {
                list.add(key);
            }
        }
        int[] result = new int[list.size()];
        for (int i = 0; i<result.length; i++) {
            result[i] = list.get(i);
        }
        return result; 
    }
    
    public void findMax(TreeNode root) {
        if (root.left != null) {
            findMax(root.left);
        }
        map.put(root.val, map.getOrDefault(root.val, 0)+1);
        max = Math.max(max, map.get(root.val));
        if (root.right != null) {
            findMax(root.right);
        }
    }
    

    03 第二种解法

    第一种解法也可以用迭代的解法来实现,思路都是一样的,只是借助栈(或者队列)来遍历节点。

    public int[] findMode2(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        int max = 0;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left != null) {
                stack.push(node.left);
            }
            map.put(node.val, map.getOrDefault(node.val, 0)+1);
            max = Math.max(max, map.get(node.val));
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        List<Integer> list = new LinkedList<>();
        for (int key: map.keySet()) {
            if (map.get(key) == max) {
                list.add(key);
            }
        }
        int[] result = new int[list.size()];
        for (int i = 0; i<result.length; i++) {
            result[i] = list.get(i);
        }
        return result;
    }
    

    04 第三种解法

    先来简单看下二叉搜索树的中序遍历,下面这个二叉搜索树中序遍历的结果为4,5,8,9,9,10,11

         9
        / 
       5   10
      /   /  
     4   8 9  11
    

    二叉搜索树在进行中序遍历后的节点值是有序排列的,并且题目中还说明了左根右节点值的关系是小于等于,因此我们只用比较当前节点值和前一个节点值即可,如果两节点值相等,当前节点值的出现次数就加1,否则次数重归于1,同时还要比较当前节点值的出现次数和历史节点值最大出现次数。

    如果当前节点的出现次数大于历史最大次数,将当前节点的出现次数赋值给历史最大次数,然后将list清空,再将节点值添加进list中;如果当前节点的出现次数等于历史最大次数,那么将当前节点值也添加进list中去。

    Integer prev = null;
    int count = 1;
    int max2 = 0;
    public int[] findMode3(TreeNode root) {
        if (root == null) {
            return new int[0];
        }   
        List<Integer> list = new ArrayList<>();
        traverse(root, list);
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); ++i) {
            res[i] = list.get(i);
        }
        return res;
    }
    
    private void traverse(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        traverse(root.left, list);
        if (prev != null) {
            if (root.val == prev) {
                count++;
            } else {
                count = 1;
            }
        }
        if (count > max2) {
            max2 = count;
            list.clear();
            list.add(root.val);
        } else if (count == max2) {
            list.add(root.val);
        }
        prev = root.val;
        traverse(root.right, list);
    }
    

    05 小结

    算法专题目前已日更超过三个月,算法题文章113+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

    以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

  • 相关阅读:
    边缘检测(13)
    图像梯度
    高斯金字塔和拉普拉斯金字塔(十一)
    轮廓发现(16)
    圆检测(15)
    直线检测(14)
    图像腐蚀与图像膨胀(18)
    go语言从例子开始之Example18_1.结构体中定义方法
    go语言从例子开始之Example18.struct结构体
    go语言从例子开始之Example17.指针
  • 原文地址:https://www.cnblogs.com/xiaochuan94/p/10360843.html
Copyright © 2020-2023  润新知