Skip to content

Commit f2fffc2

Browse files
authored
Merge pull request #277 from hellomrsun/master
Add Delete-Node-in-a-BST C#
2 parents 97fa7e5 + 8719781 commit f2fffc2

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
public class Solution {
2+
public TreeNode DeleteNode(TreeNode root, int key) {
3+
if(root == null) return null;
4+
if(key < root.val){
5+
root.left = DeleteNode(root.left, key);
6+
}else if(key > root.val){
7+
root.right = DeleteNode(root.right, key);
8+
}else{
9+
if(root.left == null)
10+
{
11+
return root.right;
12+
}
13+
else if(root.right == null){
14+
return root.left;
15+
}
16+
17+
var minNode = FindMin(root.right);
18+
root.val = minNode.val;
19+
root.right = DeleteNode(root.right, root.val);
20+
}
21+
return root;
22+
}
23+
24+
public TreeNode FindMin(TreeNode node){
25+
while(node.left != null){
26+
node = node.left;
27+
}
28+
return node;
29+
}
30+
}
31+
/**
32+
* Definition for a binary tree node.
33+
* public class TreeNode {
34+
* public int val;
35+
* public TreeNode left;
36+
* public TreeNode right;
37+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
38+
* this.val = val;
39+
* this.left = left;
40+
* this.right = right;
41+
* }
42+
* }
43+
*/

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ Solutions in various programming languages are provided. Enjoy it.
3737
28. [Implement Rand10() Using Rand7()](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7())
3838
29. [Pancake Sorting](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/29-Pancake-Sorting)
3939
30. [Largest Component Size by Common Factor](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor)
40+
31. [Delete Node in a BST](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST)
41+
4042

4143
## July LeetCoding Challenge
4244
Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions.

0 commit comments

Comments
 (0)