Swift solution - BFS, DFS


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

Log in to reply
 

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