652.find-duplicate-subtrees.go 549 B

12345678910111213141516171819202122232425
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func findDuplicateSubtrees(root *TreeNode) (res []*TreeNode) {
  10. m := make(map[string]int)
  11. helper(root, m, &res)
  12. return res
  13. }
  14. func helper(root *TreeNode, m map[string]int, res *[]*TreeNode) string {
  15. if root == nil {
  16. return "#"
  17. }
  18. path := helper(root.Left, m, res) + " " + helper(root.Right, m, res) + " " + strconv.Itoa(root.Val)
  19. if m[path] == 1 {
  20. *res = append(*res, root)
  21. }
  22. m[path]++
  23. return path
  24. }