Advertisement
Alexxik

Untitled

Sep 19th, 2023
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.58 KB | None | 0 0
  1. // MARK: - Найти одинаковые поддеревья
  2. // 625
  3.  
  4. func findDuplicateSubtrees(_ root: TreeNode?) -> [TreeNode?] {
  5.     var hashMap = [Int: Bool]()
  6.     var result = [TreeNode?]()
  7.    
  8.     func dfs(_ node: TreeNode?) -> Int {
  9.         guard let node = node else { return 0 }
  10.         let hashValue = [node.val, dfs(node.left), dfs(node.right)].hashValue
  11.         if hashMap[hashValue] == true {
  12.             result.append(node)
  13.         }
  14.         hashMap[hashValue] = hashMap[hashValue] == nil
  15.         return hashValue
  16.     }
  17.    
  18.     dfs(root)
  19.     return result
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement