From 402b6d3cf8c7b691aec2a3671586af0c03a55d30 Mon Sep 17 00:00:00 2001 From: bt3gl <138340846+bt3gl-google@users.noreply.github.com> Date: Sun, 30 Jul 2023 17:49:12 -0700 Subject: [PATCH] Create find_duplicate_subtrees.py --- trees_and_graphs/find_duplicate_subtrees.py | 39 +++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 trees_and_graphs/find_duplicate_subtrees.py diff --git a/trees_and_graphs/find_duplicate_subtrees.py b/trees_and_graphs/find_duplicate_subtrees.py new file mode 100644 index 0000000..dc6ac78 --- /dev/null +++ b/trees_and_graphs/find_duplicate_subtrees.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl +# +# Given the root of a binary tree, return all duplicate subtrees. +# +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + + +def find_duplicates(root: Optional[TreeNode]) -> List[Optional[TreeNode]]: + + result = [] + counter = {} + + def traverse(node): + if not node: + return "" + + rep = ("(" + traverse(node.left) + ")" + \ + str(node.val) + "(" + \ + traverse(node.right) + ")") + + if rep in counter: + counter[rep] += 1 + else: + counter[rep] = 1 + + if counter[rep] == 2: + result.append(node) + + return rep + + traverse(root) + return result