Swift solution - DFS


  • 0
    class Solution {
        func deleteNode(_ root: TreeNode?, _ key: Int) -> TreeNode? {
            guard let root = root else {
                return nil
            }
            
            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 == nil {
                    return root.right
                } else if root.right == nil {
                    return root.left
                } else {
                    let minNode = findMin(root.right!)
                    root.val = minNode.val
                    root.right = deleteNode(root.right, root.val)
                }
            }
            
            return root
        }
        
        func findMin(_ root: TreeNode) -> TreeNode {
            var root = root
            
            while let leftNode = root.left {
                root = leftNode
            }
            
            return root
        }
    }
    

Log in to reply
 

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