Find Duplicate Subtrees

Problem Description

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:

Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]

Example 2:

Input: root = [2,1,1]
Output: [[1]]

Example 3:

Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]

 

Constraints:

Solution (Go)

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
	dups := make(map[string][]*TreeNode)
	constructDupsMap(root, dups)
	var res []*TreeNode
	for _, l := range dups {
		if len(l) > 1 {
			res = append(res, l[0])
		}
	}
	return res
}

func constructDupsMap(root *TreeNode, dups map[string][]*TreeNode) string {
	if root == nil {
		return "#"
	}
	subtree := strconv.Itoa(root.Val)
	subtree += ";" + constructDupsMap(root.Left, dups) + ";" + constructDupsMap(root.Right, dups)
	addToDups(dups, subtree, root)
	return subtree
}

func addToDups(dups map[string][]*TreeNode, subtree string, root *TreeNode) {
	l, _ := dups[subtree]
	l = append(l, root)
	dups[subtree] = l
}