From 09e230bef32642e1e00f6223b83749a93989d70c Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 5 Dec 2023 09:08:03 +0800 Subject: [PATCH] =?UTF-8?q?Update0235.=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96?= =?UTF-8?q?=E5=85=88=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...35.二叉搜索树的最近公共祖先.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b7e92e4e..b27a231e 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -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; +} +```