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+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

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

原文地址:https://www.cnblogs.com/xiaochuan94/p/10360843.html

时间: 2024-07-29 21:54:18

LeetCode算法题-Find Mode in Binary Search Tree(Java实现)的相关文章

【leetcode刷题笔记】Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

【leetcode刷题笔记】Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 题解:需要找到二叉搜索树中乱序的两个节点,并把它们交换回来

leetcode 108 Convert Sorted Array to Binary Search Tree ----- java

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 给一个排好序的数组,然后求搜索二叉树 其实就是二分法,不难. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNo

【leetcode刷题笔记】Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example,Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 题解:递归的枚举1~n的每个节点为根节点,然后递归

leetcode - Lowest Common Ancestor of a Binary Search Tree

leetcode -  Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined

leetcode -day19 Convert Sorted List to Binary Search Tree

1.  Convert Sorted List to Binary Search Tree Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 分析:将一个升序排列的链表转换为平衡二叉搜索树,采用递归的方式,先找到链表的中点,作为二叉树的根,然后递归求解左右子树. 如下: class Solution { public: Tr

leetcode No109. Convert Sorted List to Binary Search Tree

Question: Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 把有序链表转化成平衡的BST Algorithm: 把链表转化成数组,再根据leetcode No108. Convert Sorted Array to Binary Search Tree的方法 找到数组中间的元素,作为根节点,则根节点左边是左子树,根节点

[Leetcode][BST][Convert Sorted Array to Binary Search Tree]

把一个排好序的vector转换为一颗二分查找树. 很简单的题目,递归即可,保证边界不要出错. 1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 1

[LeetCode 题解]:Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 题意:给定一个有序的链表,将其转换成平衡二叉搜索树 思路: 二分法 要构建一个平衡二叉树,二分法无疑是合适的,至于如何分是的代码简洁,就需要用到递归了. class Solution { public: // find middle element of the list Lis