Leetcode 652. 尋找重復(fù)的子樹(序列化 + 哈希表)

問題描述

給定一棵二叉樹,返回所有重復(fù)的子樹。對于同一類的重復(fù)子樹,你只需要返回其中任意一棵的根結(jié)點(diǎn)即可。
兩棵樹重復(fù)是指它們具有相同的結(jié)構(gòu)以及相同的結(jié)點(diǎn)值。

Example

輸入:[1,2,3,4,null,2,4,null,null,4]



輸出:[[2,4],[4]]


思路

對于一棵樹的子樹間的匹配問題,可以采用序列化 + 哈希表的方式來求解。通過對樹的序列化,并使用哈希表記錄對應(yīng)序列的出現(xiàn)次數(shù)。若當(dāng)前節(jié)點(diǎn) root 的序列化在哈希表中出現(xiàn)且僅出現(xiàn)過一次,則 root 就是我們要找的重復(fù)子樹

代碼

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

執(zhí)行結(jié)果: 76 ms, 49.6 MB

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容