Merge pull request #2356 from eeee0717/master

Update0235.二叉搜索树的最近公共祖先,添加C#
This commit is contained in:
程序员Carl
2023-12-08 11:57:40 +08:00
committed by GitHub
3 changed files with 53 additions and 0 deletions

View File

@ -513,6 +513,31 @@ impl Solution {
}
}
```
### C#
```C#
// 递归
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if (root.val > p.val && root.val > q.val)
return LowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val)
return LowestCommonAncestor(root.right, p, q);
return root;
}
// 迭代
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
while (root != null)
{
if (root.val > p.val && root.val > q.val)
root = root.left;
else if (root.val < p.val && root.val < q.val)
root = root.right;
else return root;
}
return null;
}
```
<p align="center">

View File

@ -567,6 +567,23 @@ impl Solution {
}
}
```
### C#
```C#
// 递归
public TreeNode TrimBST(TreeNode root, int low, int high)
{
if (root == null) return null;
if (root.val < low)
return TrimBST(root.right, low, high);
if (root.val > high)
return TrimBST(root.left, low, high);
root.left = TrimBST(root.left, low, high);
root.right = TrimBST(root.right, low, high);
return root;
}
```
<p align="center">

View File

@ -691,6 +691,17 @@ impl Solution {
}
}
```
### C#
``` C#
// 递归
public TreeNode InsertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
if (root.val > val) root.left = InsertIntoBST(root.left, val);
if (root.val < val) root.right = InsertIntoBST(root.right, val);
return root;
}
```
<p align="center">