Skip to content

Latest commit

 

History

History

652 - Find Duplicate Subtrees

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

652. Find Duplicate Subtrees share

Problem Statement

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:

  • The number of the nodes in the tree will be in the range [1, 5000]
  • -200 <= Node.val <= 200

Solutions

package main

import "strconv"

// Definition for a binary tree node.
type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
	// to store the hash value of subtrees
	hashMap := make(map[string]int)
	// to store the result
	res := make([]*TreeNode, 0)
	// traverse the tree
	traverse(root, hashMap, &res)
	return res
}

// traverse the tree
func traverse(root *TreeNode, hashMap map[string]int, res *[]*TreeNode) string {
	// if the root is nil, return "#"
	if root == nil {
		return "#"
	}
	// traverse the left and right subtree
	left := traverse(root.Left, hashMap, res)
	right := traverse(root.Right, hashMap, res)
	// get the hash value of the subtree
	subTree := left + "," + right + "," + strconv.Itoa(root.Val)
	// if the hash value of the subtree is 1, it means that the subtree is duplicated
	if hashMap[subTree] == 1 {
		*res = append(*res, root)
	}
	// add the hash value of the subtree to the hashMap
	hashMap[subTree]++
	return subTree
}