• [Leetcode]652.Find Duplicate Subtrees


    链接:LeetCode652

    给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
    两棵树重复是指它们具有相同的结构以及相同的结点值。

    相关标签:深度优先搜索

    深度优先搜索加哈希表。由于在寻找重复子树过程中,我们需要记住每一步的结果,并且最终记录是否重复,这里可以将子树存储在哈希表中,存储结构使用二叉树进行序列化即可。最终,我们只需要记录在搜索过程中重复数为2的键即可,这样防止出现2个以上重复子树时,返回了多个相同的根节点。

    代码如下:

    python:

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    import collections
    class Solution:
        def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
            res = []
            if not root:return res
            hashmap = collections.defaultdict(int)
            self.dfs(root,hashmap,'',res)
            return res
    
        def dfs(self,root,hashmap,tree,res):
            if not root:
                return tree+'#'
            left = self.dfs(root.left,hashmap,tree,res)
            right = self.dfs(root.right,hashmap,tree,res)
            tree += str(root.val)+left+right
            hashmap[tree] += 1
            # 只存储等于2的,防止重复
            if hashmap[tree]==2:
                res.append(root)
            return  tree
    
    

    C++:

    /**
     * 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) {
            vector<TreeNode*> res;
            if(!root){
                return res;
            }
            unordered_map<string,int> hashmap;
    
            dfs(root,hashmap,"",res);
            return res;
        }
    
        string dfs(TreeNode* root,unordered_map<string,int> &hashmap,string tree,vector<TreeNode*> &res){
            if(!root){
                return tree+'#';
            }
            tree += to_string(root->val)+dfs(root->left,hashmap,tree,res)+dfs(root->right,hashmap,tree,res);
            if(hashmap.find(tree)==hashmap.end()){
                hashmap[tree] = 0;
            }
            hashmap[tree] ++;
            if(hashmap[tree] == 2){
                res.push_back(root);
            }
            return tree;
        }
    };
    
  • 相关阅读:
    社区运营一点事
    从拉动APP下载谈运营
    c#基础学习(0702)之面向对象和方法重写概述
    c#基础学习(0706)之使用虚方法实现多态
    c#基础学习(0703)之string.Format格式化日期
    c#基础学习(0701)之一些简单的方法练习
    c#基础学习(0630)之面向对象总习
    c#基础学习(0629)之导出Excel方法
    c#基础学习(0628)之使用进程打开指定的文件、模拟磁盘打开文件
    c#基础学习(0627)之类型转换、算数运算符++、--
  • 原文地址:https://www.cnblogs.com/hellojamest/p/12239126.html
Copyright © 2020-2023  润新知