Update0235.二叉搜索树的最近公共祖先,添加C#

This commit is contained in:
eeee0717
2023-12-05 09:08:03 +08:00
parent f47dd60148
commit 09e230bef3

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"> <p align="center">