652. Find Duplicate Subtrees

Medium

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

解題

將樹轉換為字串記錄在 map 裡面,若出現第二次,將該樹的 root 加入答案陣列。效率有點不美好但是很好懂。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
    m := make(map[string]int)
    res := make([]*TreeNode, 0)

    var helper func(*TreeNode) 
    helper = func(root *TreeNode) {
        if root == nil { return }
        
        str := treeToArray(root)
        if m[str] == 1 {
            res = append(res, root)
            m[str]++
        } else {
            m[str]++
        }

        helper(root.Right)
        helper(root.Left)
    }

    helper(root)

    return res
}

func treeToArray(root *TreeNode) string {
    res := ""

    var helper func(*TreeNode)
    helper = func(root *TreeNode) {
        if root == nil {
            return 
        }

        res += strconv.Itoa(root.Val) + ","
        helper(root.Left)
        res +=  "*"
        helper(root.Right)
    } 

    helper(root)
    return res
}

Last updated