501. 二叉搜索树中的众数

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

假定 BST 有如下定义:

结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],

1
\
2
/
2
返回[2].

提示:如果众数超过1个,不需考虑输出顺序

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree

 1 import java.util.ArrayList;
 2 import java.util.Arrays;
 3 import java.util.List;
 4 
 5 public class FindModeInBST501 {
 6     static class TreeNode {
 7         int val;
 8         TreeNode left;
 9         TreeNode right;
10         TreeNode(int x) {
11             this.val = x;
12         }
13     }
14     
15     private TreeNode cur;
16     private int count = 1;
17     private int result = 1;
18     
19     public int[] findMode(TreeNode root) {
20         List<Integer> maxCounts = new ArrayList<>();
21         inOrder(root, maxCounts);
22         int[] res = new int[maxCounts.size()];
23         for(int i = 0 ; i < maxCounts.size(); i++) {
24             res[i] = maxCounts.get(i);
25         }
26         return res;      
27     }
28     public void inOrder(TreeNode root, List<Integer> list) {
29         if(root == null) {
30             return;
31         }
32         inOrder(root.left, list);
33         if(cur != null) {
34             if(root.val == cur.val) {
35                 count++;
36                 if(result == count) {
37                     list.add(root.val);
38                 }
39                 if(result < count) {
40                     result = count;
41                     list.clear();
42                     list.add(root.val);
43                 }
44             }else {
45                 count = 1;
46                 cur = root;
47                 if(count == result) {
48                     list.add(root.val);
49                 }
50             }
51         }else {
52             cur = root;
53             list.add(root.val);
54         }
55         inOrder(root.right, list);
56     }
57     
58     public static void main(String[] args) {
59         FindModeInBST501 t = new FindModeInBST501();
60         TreeNode root = new TreeNode(1);
61         root.right = new TreeNode(2);
62         root.right.left = new TreeNode(2);
63         System.out.println(Arrays.toString(t.findMode(root)));
64     }
65 }

 

posted @ 2019-07-11 23:37  往南的小燕子  阅读(443)  评论(0编辑  收藏  举报