LeetCode_501. Find Mode in Binary Search Tree
Posted 邓戈麟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode_501. Find Mode in Binary Search Tree相关的知识,希望对你有一定的参考价值。
501. 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).
package leetcode.easy; /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode * left; TreeNode right; TreeNode(int x) { val = x; } } */ public class FindModeInBinarySearchTree { private static void print_arr(int[] nums) { for (int num : nums) { System.out.print(num + " "); } System.out.println(); } java.util.Map<Integer, Integer> map; int max = 0; public int[] findMode(TreeNode root) { this.map = new java.util.HashMap<>(); inorder(root); java.util.List<Integer> list = new java.util.LinkedList<>(); for (int key : map.keySet()) { if (map.get(key) == max) { list.add(key); } } int[] num = new int[list.size()]; for (int i = 0; i < list.size(); i++) { num[i] = list.get(i); } return num; } public void inorder(TreeNode root) { if (root == null) { return; } map.put(root.val, map.getOrDefault(root.val, 0) + 1); if (map.get(root.val) > max) { max = map.get(root.val); } inorder(root.left); inorder(root.right); } @org.junit.Test public void test() { TreeNode tn11 = new TreeNode(1); TreeNode tn22 = new TreeNode(2); TreeNode tn33 = new TreeNode(2); tn11.left = null; tn11.right = tn22; tn22.left = tn33; tn22.right = null; tn33.left = null; tn33.right = null; print_arr(findMode(tn11)); } }
以上是关于LeetCode_501. Find Mode in Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
leetcode501. Find Mode in Binary Search Tree
LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)
[LeetCode]501. Find Mode in Binary Search Tree二叉搜索树寻找众数
LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)