my two swfit solutions


  • 0
    W

    solution 1 :

    func minDepth(_ root: TreeNode?) -> Int {
            if root == nil {return 0}
            
            if root!.left == nil && root!.right != nil {
                return minDepth(root!.right) + 1
            }
            
            if root!.left != nil && root!.right == nil {
                return minDepth(root!.left) + 1
            }
            
            if root!.left == nil && root!.right == nil {
                return 1
            }
            
            return min(minDepth(root!.left) + 1, minDepth(root!.right) + 1)
            
        }
    

    solution 2:

    func minDepth(_ root: TreeNode?) -> Int {
        if root == nil {return 0}
        var depth = 0
        var arr = [TreeNode]()
        arr.append(root!)
        while arr.count > 0 {
            let count = arr.count
            depth += 1
            for _ in 0..<count {
                let node = arr.removeFirst()
                if node.left == nil && node.right == nil {
                    return depth
                }
                if node.left != nil {arr.append(node.left!)}
                if node.right != nil {arr.append(node.right!)}
            }
        }
        
        return depth
    }
    

Log in to reply
 

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