1. 程式人生 > >[LeetCode] Find Duplicate Subtrees 尋找重複樹

[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: 

        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.

這道題讓我們尋找重複樹,博主開始的思路是遍歷每個結點,將結點值相同的結點放到一起,如果再遇到相同的結點值,則呼叫一個判斷是否是相同樹的子函式,但是這樣會有大量的重複運算,會TLE。後來去網上看大神們的解法,發現果然是很叼啊,用到了後序遍歷,還有陣列序列化,並且建立序列化跟其出現次數的對映,這樣如果我們得到某個結點的序列化字串,而該字串正好出現的次數為1,說明之前已經有一個重複樹了,我們將當前結點存入結果res,這樣保證了多個重複樹只會存入一個結點,參見程式碼如下:

class Solution {
public:
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        vector<TreeNode*> res;
        unordered_map<string, int> m;
        helper(root, m, res);
        return res;
    }
    string helper(TreeNode* node, unordered_map<string
, int>& m, vector<TreeNode*>& res) { if (!node) return "#"; string str = to_string(node->val) + "," + helper(node->left, m, res) + "," + helper(node->right, m, res); if (m[str] == 1) res.push_back(node); ++m[str]; return str; } };

參考資料: