Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to find duplicate subtrees in python binary trees

Shulou Source: shulou.com Published: 2022-06-01 14:12:26 10月12日 Update

This article introduces the python binary tree how to find duplicate subtrees, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.

Given a binary tree, return all duplicate subtrees. For the same kind of repeated subtrees, you only need to return to the root node of any one of them.

Repetition of two trees means that they have the same structure and the same node value.

Example 1:

one

/\

2 3

/ /\

4 2 4

/

four

Here are two duplicate subtrees:

two

/

four

And

four

Therefore, you need to return the root node of the repeating subtree as a list.

Ideas for solving the problem:

1, repetitive subtree means from root node to leaf node.

2. Repeat many times and take only one, so use hash to save the number of times, and take the number of times 2 as the dismissal

3, although preorder + mid-order traversal can restore the binary tree, but for different binary trees with the same element value, the preorder and mid-order traversal results are the same and can not be distinguished.

0 and 0

/\

0 0

4, so use leetcode serialization method, with special characters to indicate that the child is null, and then first order traversal, can uniquely represent a subtree.

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

Func serllize (root * TreeNode,s map [string] int) (map [string] int, [] * TreeNode) {var tn [] * TreeNode if root==nil {return sdaga tn} s1:=ts (root) s [S1] + + if s [S1] = 2 {tn=append (tn,root)} sl,l:=serllize (root.Left,s) sr,r:=serllize (root.Right,sl) tn=append (tn,l...) Tn=append (tn,r...) Return sr,tn}

Func ts (root * TreeNode) (string) {s+=fmt.Sprintf ("% d", root.Val) + "," l:=ts (root.Left) sduplicl r:=ts (root.Right) sduplicr} return s} about how to find duplicate subtrees of python binary tree is shared here. I hope the above content can be helpful to you. You can learn more. If you think the article is good, you can share it for more people to see.

Tags: Subtree same node content more times node help different good special two element interest leaf character child boy buddy sequence Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Xiaomi MySQL Shulou Technology Docker