Merge pull request #2349 from eeee0717/master

Update 0700.二叉搜索树,添加C#
This commit is contained in:
程序员Carl
2023-12-01 09:47:55 +08:00
committed by GitHub
3 changed files with 57 additions and 0 deletions

View File

@ -791,6 +791,20 @@ impl Solution {
} }
} }
``` ```
### C#
```C#
// 递归
public long val = Int64.MinValue;
public bool IsValidBST(TreeNode root)
{
if (root == null) return true;
bool left = IsValidBST(root.left);
if (root.val > val) val = root.val;
else return false;
bool right = IsValidBST(root.right);
return left && right;
}
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">

View File

@ -647,6 +647,27 @@ impl Solution {
} }
} }
``` ```
### C#
```C#
// 递归
public class Solution
{
public List<int> res = new List<int>();
public int GetMinimumDifference(TreeNode root)
{
Traversal(root);
return res.SelectMany((x, i) => res.Skip(i + 1).Select(y => Math.Abs(x - y))).Min();
}
public void Traversal(TreeNode root)
{
if (root == null) return;
Traversal(root.left);
res.Add(root.val);
Traversal(root.right);
}
}
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">

View File

@ -464,6 +464,28 @@ impl Solution {
} }
} }
``` ```
### C#
```C#
// 递归
public TreeNode SearchBST(TreeNode root, int val)
{
if (root == null || root.val == val) return root;
if (root.val > val) return SearchBST(root.left, val);
if (root.val < val) return SearchBST(root.right, val);
return null;
}
// 迭代
public TreeNode SearchBST(TreeNode root, int val)
{
while (root != null)
{
if (root.val > val) root = root.left;
else if (root.val < val) root = root.right;
else return root;
}
return null;
}
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">