Skip to content

Commit 16c38cc

Browse files
committed
652. Find Duplicate Subtrees
1 parent 1fb7b93 commit 16c38cc

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,7 @@ Check this [golden](https://tinyurl.com/ujopecz) post.
470470
|41| [938. Range Sum of BST](https://tinyurl.com/r43zu3p) | [Python](https://tinyurl.com/wu6rdaw/938_Range_Sum_of_BST.py), [Swift](https://tinyurl.com/wuja3c4/938_Range_Sum_of_BST.swift) | -- | Medium | -- |
471471
|42| [1305. All Elements in Two Binary Search Trees](https://tinyurl.com/undhmra) | [Python](https://tinyurl.com/wu6rdaw/1305_All_Elements_in_Two_Binary_Search_Trees.py), [Swift](https://tinyurl.com/wuja3c4/1305_All_Elements_in_Two_Binary_Search_Trees.swift) | -- | Medium | -- |
472472
|43| [536. Construct Binary Tree from String](https://tinyurl.com/yyl5vuh7) | [Python](https://tinyurl.com/wu6rdaw/536_Construct_Binary_Tree_from_String.py), [Swift](https://tinyurl.com/wuja3c4/536_Construct_Binary_Tree_from_String.swift) | -- | Medium | -- |
473+
|44| [652. Find Duplicate Subtrees](https://tinyurl.com/y5zt6392) | [Python](https://tinyurl.com/wu6rdaw/652_Find_Duplicate_Subtrees.py), [Swift](https://tinyurl.com/wuja3c4/652_Find_Duplicate_Subtrees.swift) | -- | Medium | -- |
473474

474475
</p>
475476
</details>
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public var val: Int
5+
* public var left: TreeNode?
6+
* public var right: TreeNode?
7+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
8+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
9+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
10+
* self.val = val
11+
* self.left = left
12+
* self.right = right
13+
* }
14+
* }
15+
*/
16+
import Foundation
17+
18+
class Solution {
19+
func findDuplicateSubtrees(_ root: TreeNode?) -> [TreeNode?] {
20+
guard let root = root else {
21+
return []
22+
}
23+
24+
var counter = [[String]:Int]()
25+
var duplicates = [TreeNode]()
26+
27+
nodeCountDFS(root, &counter, &duplicates)
28+
29+
return duplicates
30+
}
31+
32+
func nodeCountDFS(_ root: TreeNode?, _ counter: inout [[String]:Int], _ duplicates: inout [TreeNode]) -> [String] {
33+
guard let root = root else {
34+
return ["#"]
35+
}
36+
37+
var inorder = [String]()
38+
let left = nodeCountDFS(root.left, &counter, &duplicates)
39+
let right = nodeCountDFS(root.right, &counter, &duplicates)
40+
inorder = left + [String(root.val)] + right
41+
counter[inorder, default: 0] += 1
42+
43+
if counter[inorder] == 2 {
44+
duplicates.append(root)
45+
}
46+
47+
return inorder
48+
}
49+
}

0 commit comments

Comments
 (0)