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; +} +```

diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 00186558..229a2ab1 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -567,6 +567,23 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public TreeNode TrimBST(TreeNode root, int low, int high) +{ + if (root == null) return null; + if (root.val < low) + return TrimBST(root.right, low, high); + + if (root.val > high) + return TrimBST(root.left, low, high); + + root.left = TrimBST(root.left, low, high); + root.right = TrimBST(root.right, low, high); + return root; +} +```

diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 265bbb5b..98e60d5f 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -691,6 +691,17 @@ impl Solution { } } ``` +### C# +``` C# +// 递归 +public TreeNode InsertIntoBST(TreeNode root, int val) { + if (root == null) return new TreeNode(val); + + if (root.val > val) root.left = InsertIntoBST(root.left, val); + if (root.val < val) root.right = InsertIntoBST(root.right, val); + return root; +} +```