diff --git a/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.cs b/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.cs new file mode 100644 index 0000000..e6cdf73 --- /dev/null +++ b/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.cs @@ -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; + * } + * } + */ \ No newline at end of file diff --git a/README.md b/README.md index a349120..53a6b2b 100644 --- a/README.md +++ b/README.md @@ -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.