27. Find Duplicate Subtrees
Last updated
Was this helpful?
Last updated
Was this helpful?
Given the root
of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Example 2:
Example 3:
Approach: Two tree are same if they have the same structure along with same node values. So we can serialize a tree: So same tree have same serialized string and we can use map to store it.
Performing Postorder traversal and strong the string of root node as Node->val , left subtree, right subtree and NULL represented with #
Time Complexity: O(n)