[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;
    }
};

 

參考資料:

https://discuss.leetcode.com/topic/97584/java-concise-postorder-traversal-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM