BFS - Swift


  • 0
    class Solution {
        func findSecondMinimumValue(_ root: TreeNode?) -> Int {
            guard let root = root else { return -1 }
            
            var secondMinValue = Int.max
            var queue = [root]
            
            while !queue.isEmpty {
                let count = queue.count
                for _ in 0..<count {
                    let node = queue.removeFirst()
                    if node.val != root.val && node.val < secondMinValue {
                        secondMinValue = node.val
                    }
                    if let leftNode = node.left {
                        queue.append(leftNode)
                    }
                    if let rightNode = node.right {
                        queue.append(rightNode)
                    }
                }
            }
            
            return secondMinValue == Int.max ? -1 : secondMinValue
        }
    }
    

Log in to reply
 

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