Skip to content

Add Delete-Node-in-a-BST C# #277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
public class Solution {
public TreeNode DeleteNode(TreeNode root, int key) {
if(root == null) return null;
if(key < root.val){
root.left = DeleteNode(root.left, key);
}else if(key > root.val){
root.right = DeleteNode(root.right, key);
}else{
if(root.left == null)
{
return root.right;
}
else if(root.right == null){
return root.left;
}

var minNode = FindMin(root.right);
root.val = minNode.val;
root.right = DeleteNode(root.right, root.val);
}
return root;
}

public TreeNode FindMin(TreeNode node){
while(node.left != null){
node = node.left;
}
return node;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Solutions in various programming languages are provided. Enjoy it.
28. [Implement Rand10() Using Rand7()](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7())
29. [Pancake Sorting](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/29-Pancake-Sorting)
30. [Largest Component Size by Common Factor](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor)
31. [Delete Node in a BST](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST)


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