Swift solution - Stack


  • 0
    class Solution {
        func isValidSerialization(_ preorder: String) -> Bool {
            let nodes = preorder.components(separatedBy: ",")
            var stack = [String]()
            
            for i in 0..<nodes.count {
                let node = nodes[i]
                while node == "#" && !stack.isEmpty && stack.last! == "#" {
                    stack.removeLast()
                    if stack.isEmpty {
                        return false
                    }
                    stack.removeLast()
                }
                stack.append(node)
            }
            
            return stack.count == 1 && stack.last! == "#"
        }
    }
    

Log in to reply
 

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