Skip to content

Commit 7958195

Browse files
committed
BST find modes
1 parent 5744be6 commit 7958195

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Tree/Tree.TreeLib/FindModes.cs

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
6+
namespace Tree.TreeLib
7+
{
8+
// Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
9+
10+
//Assume a BST is defined as follows:
11+
12+
//The left subtree of a node contains only nodes with keys less than or equal to the node's key.
13+
//The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
14+
//Both the left and right subtrees must also be binary search trees.
15+
//For example:
16+
//Given BST [1,null,2,2],
17+
// 1
18+
// \
19+
// 2
20+
// /
21+
// 2
22+
//return [2].
23+
24+
//求解二叉搜索树中出现次数最多的元素,答案的空间复杂度为 O(1)。
25+
//二叉搜索树的中序遍历恰好为元素的从小到大排序,这样相等的元素一定是相邻的。
26+
//了解了这个知识点,空间复杂度O(1)就可以做到了。
27+
public class Findmodes
28+
{
29+
private int currentVal;
30+
private int currentCount = 0;
31+
private int maxCount = 0;
32+
private int modeCount = 0;
33+
private int[] modeArray;
34+
35+
public int[] FindMode(TreeNode root)
36+
{
37+
preorder(root); //第一遍中序遍历找出出现次数最多的元素数,可能有多个最大
38+
modeArray = new int[modeCount];
39+
modeCount = 0;
40+
currentCount = 0;
41+
preorder(root);
42+
return modeArray;
43+
}
44+
45+
/// <summary>
46+
/// 这种方法只适应于二叉搜索树条件下,查找元素出现的最多次数
47+
/// </summary>
48+
/// <param name="val"></param>
49+
private void getModeValue(int val)
50+
{
51+
if (val != currentVal)
52+
{
53+
currentVal = val;
54+
currentCount = 0;
55+
}
56+
currentCount++;
57+
if (currentCount > maxCount)
58+
{
59+
maxCount = currentCount;
60+
modeCount = 1;
61+
}
62+
else if (currentCount == maxCount)
63+
{
64+
if (modeArray != null) //第二遍遍历后,对出现次数最多的元素
65+
modeArray[modeCount] = currentVal; //依次赋值给modeArray
66+
modeCount++;
67+
}
68+
}
69+
70+
/// <summary>
71+
/// 二叉搜索树,采取中序遍历对值处理
72+
/// </summary>
73+
/// <param name="root"></param>
74+
private void preorder(TreeNode root)
75+
{
76+
if (root == null)
77+
return;
78+
preorder(root.left);
79+
getModeValue(root.val);
80+
preorder(root.right);
81+
}
82+
}
83+
}

0 commit comments

Comments
 (0)