Divide and Conquer - Swift


  • 0
    class Solution {
        func trimBST(_ root: TreeNode?, _ L: Int, _ R: Int) -> TreeNode? {
            guard let root = root else { return nil }
            
            var newRoot : TreeNode? = nil
            
            if root.val < L {
                newRoot = trimBST(root.right, L, R)
            } else if root.val > R {
                newRoot = trimBST(root.left, L, R)
            } else {
                newRoot = root
                newRoot?.left = trimBST(root.left, L, R)
                newRoot?.right = trimBST(root.right, L, R)
            }
            
            return newRoot
        }
    }
    

Log in to reply
 

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