mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #2356 from eeee0717/master
Update0235.二叉搜索树的最近公共祖先,添加C#
This commit is contained in:
@ -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">
|
||||
|
@ -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">
|
||||
|
@ -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">
|
||||
|
Reference in New Issue
Block a user