2
* Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode3
* right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left,4
* TreeNode right) { this.val = val; this.left = left; this.right = right; } }7
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {8
List<TreeNode> list = new ArrayList<TreeNode>();9
HashSet<String> hashes = new HashSet<String>();10
HashSet<String> added = new HashSet<String>();12
// for each node, perform a dfs traversal and generate a hash13
// check if the hash already exists in a set,14
// if it does, get the treenode and add it to the list15
Stack<TreeNode> s = new Stack<TreeNode>();18
while (!s.isEmpty()) {19
TreeNode tmp = s.pop();20
dfs(tmp, "", tmp, list, hashes, added);22
if (tmp.left != null) {25
if (tmp.right != null) {39
HashSet<String> added) {41
Stack<TreeNode> stack = new Stack<TreeNode>();45
hash += root.val + "ROOT,";46
while (!stack.isEmpty()) {47
TreeNode tmp = stack.pop();48
// hash += tmp.val + ",";50
if (tmp.left != null) {51
hash += tmp.left.val + "L,";56
if (tmp.right != null) {57
hash += tmp.right.val + "R,";62
if (tmp.left == null && tmp.right == null && stack.isEmpty()) {63
if (set.contains(hash)) {64
if (!added.contains(hash)) {