C# recursive solution and a helpful video..


  • 0
    K

    This video is very helpful for the algorithm
    https://www.youtube.com/watch?v=vhN9wSEy-ko

    public class Solution {
        
        public TreeNode FindMin(TreeNode root){
            
            while (root.left != null){
                root = root.left;
            }
            return root;
        }
        
        public TreeNode DeleteNodeBST(TreeNode root, int key) {
            
            if (root.right == null && root.left == null)
                root = null;
            else if (root.right == null)
                root = root.left;
            else if (root.left == null)
                root = root.right;
            else{
                TreeNode minNode = FindMin(root.right);
                root.val = minNode.val;
                root.right = DeleteNode(root.right, minNode.val);
            }
            return root;        
        }   
        
        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 (key == root.val){
                root = DeleteNodeBST(root,key);
            return root;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.