Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 09e230b

Browse files
committed
Update0235.二叉搜索树的最近公共祖先,添加C#
1 parent f47dd60 commit 09e230b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

‎problems/0235.二叉搜索树的最近公共祖先.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,31 @@ impl Solution {
513513
}
514514
}
515515
```
516+
### C#
517+
```C#
518+
// 递归
519+
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
520+
{
521+
if (root.val > p.val && root.val > q.val)
522+
return LowestCommonAncestor(root.left, p, q);
523+
if (root.val < p.val && root.val < q.val)
524+
return LowestCommonAncestor(root.right, p, q);
525+
return root;
526+
}
527+
// 迭代
528+
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
529+
{
530+
while (root != null)
531+
{
532+
if (root.val > p.val && root.val > q.val)
533+
root = root.left;
534+
else if (root.val < p.val && root.val < q.val)
535+
root = root.right;
536+
else return root;
537+
}
538+
return null;
539+
}
540+
```
516541

517542

518543
<p align="center">

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /