mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
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">
|
<p align="center">
|
||||||
|
Reference in New Issue
Block a user