首页 > 其他 > 详细

LeetCode 652. Find Duplicate Subtrees

时间:2018-09-14 10:20:45      阅读:164      评论:0      收藏:0      [点我收藏+]

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

时间复杂度,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;
    }
};

 

LeetCode 652. Find Duplicate Subtrees

原文:https://www.cnblogs.com/hankunyan/p/9644540.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!