ac solution code


  • 0

    Solution1. Recursive Binary Search - time = O(lgn); space = O(1)

    func closestValue(_ root: TreeNode?, _ target: Double) -> Int {
        guard let root = root else { return 0 }
        
        let curVal = Double(root.val)
        // 1. Compare target and curNode's value
        // 2-1. 2 directions: left/right kids
        let kid = target < curVal ? root.left : root.right
        // 2-2. return curNode if it's leaf
        if kid == nil { return Int(curVal) }
        // 3. Keep recusion
        let kidVal = Double(closestValue(kid, target))
        // 4. Result: Choose closer one between curNode and kidNode
        return abs(curVal - target) < abs(kidVal - target) ? Int(curVal): Int(kidVal)
    }
    

Log in to reply
 

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