Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Find Duplicate Subtrees

Posted on March 16, 2018July 26, 2020 by braindenny

Find Duplicate Subtrees



Similar Problems:

  • LeetCode: Brick Wall
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #classic, #inspiring, #binarytree, #hashmap, #postorder, #findduplicates

Given 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 same node values.

Example 1:

    1
   / \
  2   3
 /   / \
4   2   4
   /
  4

The following are two duplicate subtrees:

  2
 /
4

and

4

Therefore, you need to return above trees’ root in the form of a list.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/find-duplicate-subtrees
// Basic Ideas: hashmap
// Encode binarytree to string
// Complexity: Time O(n), Space O(n)
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
    m := map[string]int{}
    res := []*TreeNode{}
    postTree(root, m, &res)
    return res
}

func postTree(root *TreeNode, m map[string]int, res *[]*TreeNode) string {
    if root == nil { return "#" }
    l, r := postTree(root.Left, m, res), postTree(root.Right, m, res)
    v := fmt.Sprintf("%s,%s,%d", l, r, root.Val)
    if m[v] == 1 { *res = append(*res, root) }
    m[v]++
    return v
}
linkedin
github
slack

Post Views: 6
Posted in BasicTagged #binarytree, #classic, #inspiring, findduplicates, hashmap, postorder

Post navigation

LeetCode: Find Median Given Frequency of Numbers
LeetCode: Valid Parenthesis String

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.