LeetCode 652. Find Duplicate Subtrees

后序遍历,把每个节点的后序遍历用字符串保存下来。

时间复杂度,T(n)=2T(n/2)+n (字符串处理) = O(nlogn),最坏 O(n^2)。

空间复杂度,每个节点都要字符串来存,O(n^2)。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode *> res;
    multiset<string> s;
    
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        dfs(root);
        return res;
    }
    
    string dfs(TreeNode* root){
        if (root==NULL) return "#";
        string left=dfs(root->left);
        string right=dfs(root->right);
        string cur=to_string(root->val)+left+right;
        if (s.count(cur)==1) res.push_back(root);
        s.insert(cur);
        return cur;
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9644540.html