Swift BFS Solution


  • 0
    D

    Swift Solution with BFS:

       func findBottomLeftValue(_ root: TreeNode?) -> Int {
            var currentLevel = [TreeNode]()
            var nextLevel = [TreeNode]()
            var nextFirstNodeVal = root!.val
            
            currentLevel.append(root!)
            
            while currentLevel.count > 0 {
                var currNode = currentLevel.removeFirst()
                if let left = currNode.left {
                    nextLevel.append(left)
                }
                if let right = currNode.right {
                    nextLevel.append(right)
                }
                if currentLevel.count == 0 {
                    currentLevel = nextLevel
                    if nextLevel.count > 0 { nextFirstNodeVal = nextLevel[0].val }
                    nextLevel = []
                }
            }
            return nextFirstNodeVal
        }
    }
    

Log in to reply
 

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