-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_34.java
More file actions
60 lines (49 loc) · 1.52 KB
/
Copy pathBT_Problem_34.java
File metadata and controls
60 lines (49 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package trees.binaryTree;
import java.util.*;
// Problem Title => Find all Duplicate subtrees in a Binary tree [ IMP ]
public class BT_Problem_34 {
static HashMap<String, Integer> m;
static class Node{
int data;
Node left,right;
Node(int data){
this.data = data;
left = right = null;
}
}
static String inorder(Node node){
if(node == null) return "";
String str = "(";
str += inorder(node.left);
str += Integer.toString(node.data);
str += inorder(node.right);
str += ")";
// Subtree already present
// (Note that we use HashMap instead of HashSet because we want to print multiple duplicates only once,
// consider example of 4 in above subtree,
// it should be printed only once.
if (m.get(str) != null && m.get(str)==1 )
System.out.print( node.data + " ");
if (m.containsKey(str))
m.put(str, m.get(str) + 1);
else
m.put(str, 1);
return str;
}
static void printAllDups(Node root) {
m = new HashMap<>();
inorder(root);
}
// Driver code
public static void main(String[] args) {
Node root;
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(2);
root.right.left.left = new Node(4);
root.right.right = new Node(4);
printAllDups(root);
}
}