Day8-9
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_235._Lowest_Common_Ancestor_of_a_Binary_Search_Tree</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace _235._Lowest_Common_Ancestor_of_a_Binary_Search_Tree;
|
||||
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
TreeNode root = new TreeNode(6);
|
||||
root.left = new TreeNode(2) { left = new TreeNode(0), right = new TreeNode(4) { left = new TreeNode(3), right = new TreeNode(5) } };
|
||||
root.right = new TreeNode(8) { left = new TreeNode(7), right = new TreeNode(9) };
|
||||
Console.WriteLine(new Solution().LowestCommonAncestor(root, new TreeNode(3), new TreeNode(5)).val);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace _235._Lowest_Common_Ancestor_of_a_Binary_Search_Tree;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public TreeNode? LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
|
||||
{
|
||||
int min = Math.Min(p.val, q.val);
|
||||
int max = Math.Max(p.val, q.val);
|
||||
while(true)
|
||||
{
|
||||
if (root == null)
|
||||
return null;
|
||||
else if (min <= root.val && max>=root.val)
|
||||
return root;
|
||||
else if (root.val >= p.val)
|
||||
root = root.left!;
|
||||
else
|
||||
root = root.right!;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace _235._Lowest_Common_Ancestor_of_a_Binary_Search_Tree;
|
||||
|
||||
//Definition for a binary tree node.
|
||||
public class TreeNode {
|
||||
public int val;
|
||||
public TreeNode? left;
|
||||
public TreeNode? right;
|
||||
public TreeNode(int x) { val = x; }
|
||||
}
|
||||
Reference in New Issue
Block a user