contains category wise problems(data structures, competitive) of popular platforms.
View the Project on GitHub mayankdutta/category-wise-problems
subtree always involves leaves therefore evolving from leaf seems better idea.
In post order priority is given toleft
,right
then to leaf.
subtree from leaf to root
and store them in map.occurrence = 2
store in the answer, that value is the final, it wont be updating again.class Solution {
HashMap<String, Integer> map;
ArrayList<TreeNode> arr;
public String pre(TreeNode root) {
if (root == null)
return "#";
String left = pre(root.left);
String right = pre(root.right);
String curr = left + "," + right + "," + Integer.toString(root.val);
map.put(curr, map.getOrDefault(curr, 0) + 1);
if (map.get(curr) == 2)
arr.add(root);
return curr;
}
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
map = new HashMap<>();
arr = new ArrayList<>();
String ans = pre(root);
return arr;
}
}