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).
解题:给一个二叉查找树,返回出现次数最多的元素(众数)。并且要求不使用额外的空间,要求结果以数组的形式返回。我使用了一个ArrayList,有额外的空间消耗,虽然不满足条件,但是比较简单方便。当然也可以把数组定义为成员变量,由于数组的长度不知道,还得定义一个末尾指针,太麻烦,不如用集合。思路是,遍历BST,由于其本身的性质,遍历的过程中得到的序列,就是一个有序序列。定一个max用来保存出现做多的次数,pre记录父节点,如果没有,则为空。再定义一个res的集合保存结果,定一个cns保存当前出现最多的次数(暂时),然后不断地比较cns和max的值,随时更新res结果集,代码如下:
1 /**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 * int val;
5 * TreeNode left;
6 * TreeNode right;
7 * TreeNode(int x) { val = x; }
8 * }
9 */
10 class Solution {
11 ArrayList<Integer>res = null;
12 TreeNode pre = null;
13 int max = 0;
14 int cns = 1;
15 public int[] findMode(TreeNode root) {
16 //存放结果
17 res = new ArrayList<Integer>();
18 middle_search(root);
19 int[] arr =new int[res.size()];
20 for(int i =0; i < arr.length; i++)
21 arr[i] = res.get(i);
22 return arr;
23 }
24 public void middle_search(TreeNode root) {
25 if(root == null)
26 return ;
27 middle_search(root.left);
28 //处理根结点
29 if(pre != null){ //有父节点
30 if(root.val == pre.val)
31 cns++;
32 else cns = 1;
33 }
34 if(cns >= max){
35 if(cns > max)
36 res.clear();
37 max = cns;
38 res.add(root.val);
39 }
40 pre = root;
41
42 middle_search(root.right);
43 }
44 }