mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
Create find_duplicate_subtrees.py
This commit is contained in:
parent
2e37835477
commit
402b6d3cf8
39
trees_and_graphs/find_duplicate_subtrees.py
Normal file
39
trees_and_graphs/find_duplicate_subtrees.py
Normal file
@ -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
|
Loading…
x
Reference in New Issue
Block a user