Swift 3 DFS Hashset Solution


  • 0
    Y
    func checkEqualTree(_ root: TreeNode?) -> Bool {
            if root == nil || root!.left == nil && root!.right == nil {
                // corner case [0] []
                return false
            }
            var set = Set<Int>()
            var sum = dfs(root, &set)
            // sum must be even and set contains half of sum
            return sum % 2 == 0 && set.contains(sum / 2)
        }
        
        func dfs(_ root: TreeNode?, _ set: inout Set<Int>) -> Int {
            guard let root = root else { return 0 }
            var sum = dfs(root.left, &set) + dfs(root.right, &set) + root.val 
            set.insert(sum)
            return sum
        }
    

Log in to reply
 

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