美文网首页LeeCode题目笔记
2019-11-19 寻找重复的子树

2019-11-19 寻找重复的子树

作者: Antrn | 来源:发表于2019-11-19 21:12 被阅读0次

给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。

两棵树重复是指它们具有相同的结构以及相同的结点值。

示例 1:

    1
   / \
  2   3
 /   / \
4   2   4
   /
  4

下面是两个重复的子树:

  2
 /
4

4

因此,你需要以列表的形式返回上述重复子树的根结点。

C++1
/**
 * 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*> findDuplicateSubtrees(TreeNode* root) {
        map<string, int> m;
        vector<TreeNode*> res;
        _dfs(root, m, res);
        return res;
        
    }
    string _dfs(TreeNode* root, map<string, int>& m, vector<TreeNode*>& res){
        if (not root) return "-";
        string path = to_string(root->val) + _dfs(root->left, m, res) + _dfs(root->right, m, res);
        if (m[path] == 1)
            res.push_back(root);
        m[path] = m[path] + 1;
        return path;            
    }
};

相关文章

网友评论

    本文标题:2019-11-19 寻找重复的子树

    本文链接:https://www.haomeiwen.com/subject/ubggictx.html