generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem40.cs
37 lines (35 loc) · 1.13 KB
/
Problem40.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">Lowest Common Ancestor of a Binary Search Tree</see>.
/// </summary>
public static class Problem40
{
/// <summary>
/// Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="root">Binary search tree to traverse.</param>
/// <param name="p">Node p.</param>
/// <param name="q">Node q.</param>
/// <returns>Lowest common ancestor of two given nodes.</returns>
public static TreeNode? LowestCommonAncestor(TreeNode? root, TreeNode p, TreeNode q)
{
if (root == null)
{
return null;
}
if (p.Val < root.Val && q.Val < root.Val)
{
return LowestCommonAncestor(root.Left, p, q);
}
else if (p.Val > root.Val && q.Val > root.Val)
{
return LowestCommonAncestor(root.Right, p, q);
}
else
{
return root;
}
}
}