天天看點

[LeetCode] Find Duplicate Subtrees 尋找重複樹

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

Two trees are duplicate if they have the same structure with same node values.

Example 1: 

The following are two duplicate subtrees:

and

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

 這道題讓我們尋找重複樹,部落客開始的思路是周遊每個結點,将結點值相同的結點放到一起,如果再遇到相同的結點值,則調用一個判斷是否是相同樹的子函數,但是這樣會有大量的重複運算,會TLE。後來去網上看大神們的解法,發現果然是很叼啊,用到了後序周遊,還有數組序列化,并且建立序列化跟其出現次數的映射,這樣如果我們得到某個結點的序列化字元串,而該字元串正好出現的次數為1,說明之前已經有一個重複樹了,我們将目前結點存入結果res,這樣保證了多個重複樹隻會存入一個結點,參見代碼如下:

<a>class Solution {</a>

參考資料:

<a href="https://discuss.leetcode.com/topic/97584/java-concise-postorder-traversal-solution">https://discuss.leetcode.com/topic/97584/java-concise-postorder-traversal-solution</a>

,如需轉載請自行聯系原部落客。