mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #2352 from eeee0717/master
Update 0501.二叉搜索树中的众数,添加C#版
This commit is contained in:
@ -431,6 +431,19 @@ impl Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
### C#
|
||||
```C#
|
||||
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
|
||||
{
|
||||
if (root == null || root == p || root == q) return root;
|
||||
TreeNode left = LowestCommonAncestor(root.left, p, q);
|
||||
TreeNode right = LowestCommonAncestor(root.right, p, q);
|
||||
if (left != null && right != null) return root;
|
||||
if (left == null && right != null) return right;
|
||||
if (left != null && right == null) return left;
|
||||
return null;
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
@ -1009,6 +1009,46 @@ pub fn find_mode(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
||||
res
|
||||
}
|
||||
```
|
||||
### C#
|
||||
```C#
|
||||
// 递归
|
||||
public class Solution
|
||||
{
|
||||
public List<int> res = new List<int>();
|
||||
public int count = 0;
|
||||
public int maxCount = 0;
|
||||
public TreeNode pre = null;
|
||||
public int[] FindMode(TreeNode root)
|
||||
{
|
||||
SearchBST(root);
|
||||
return res.ToArray();
|
||||
}
|
||||
public void SearchBST(TreeNode root)
|
||||
{
|
||||
if (root == null) return;
|
||||
SearchBST(root.left);
|
||||
if (pre == null)
|
||||
count = 1;
|
||||
else if (pre.val == root.val)
|
||||
count++;
|
||||
else
|
||||
count = 1;
|
||||
|
||||
pre = root;
|
||||
if (count == maxCount)
|
||||
{
|
||||
res.Add(root.val);
|
||||
}
|
||||
else if (count > maxCount)
|
||||
{
|
||||
res.Clear();
|
||||
res.Add(root.val);
|
||||
maxCount = count;
|
||||
}
|
||||
SearchBST(root.right);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
<p align="center">
|
||||
|
Reference in New Issue
Block a user