501. Find Mode in Binary Search Tree | 二叉搜索树重复的节点

本文介绍了一种寻找二叉搜索树中最常出现元素的方法。通过中序遍历将节点值存入映射表,并统计每个元素出现次数,进而找到出现频率最高的元素。文章还提出了一种更高效的递归解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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).

Subscribe to see which companies asked this question.


思路:我的这个方法用了很多额外的控件,但是比较好理解,先终于遍历将节点存入map里面,value值为那个值的个数,在找出value最大的值,对应的key存入数组。

public class Solution {
    public int[] findMode(TreeNode root) {
		int[] a = new int[] {};
		List<Integer> list = new ArrayList<>();
		Map<Integer, Integer> map = new HashMap<>();
		Stack<TreeNode> stack = new Stack<>();
		while (!stack.isEmpty() || root != null) {
			while (root != null) {
				stack.push(root);
				root = root.left;
			}
			root = stack.pop();
			map.put(root.val, map.getOrDefault(root.val, 0) + 1);
			root = root.right;
		}

		int max = 0;
		Iterator iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			int val = (int) entry.getValue();
			if (val > max) {
				max = val;
			}
		}

		iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			int key = (int) entry.getKey();
			int val = (int) entry.getValue();
			if (val == max) {
				list.add(key);
			}
		}

		a = new int[list.size()];
		for (int i = 0; i < list.size(); i++) {
			a[i] = list.get(i);
		}
		return a;
	}
}



可以看到,对象多了后,时间也是好长。。。

看到答案的一种方法就是用递归,在递归的时候记录个数,因为二叉搜索树中序遍历的话是有序的如果相同则会在前后一起,同时记录前一个节点的值,并和当前节点的值比较,如果个数大于了当前的max(相同值的节点的数量),则list先清除之前插入的,然后插入当前节点的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值