I want to write a method to find whether a tree has at least a pair of identical subtrees, the subtrees have to be identical in both value and structure.
Suppose you are given a tree as follows:
a
/ \
b f
/ / \
c g d
/ / /
d h e
/
e
This would return true because we have a pair of identical trees with root d.
My thought is to traverse each node and build a map of node name mapped to list of tree nodes. In each iteration, we check if current node name is in the map or not. If it's in, then we can call boolean isSameTree(TreeNode t1, TreeNode t2) function with current node against every node in the list of tree nodes to see if they are identical.
The time complexity would be O(n^3). And I wonder if we can do better than that!