LeetCode 652 Find Duplicate Subtrees (dfs 推荐)

244 篇文章 0 订阅
16 篇文章 0 订阅

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with the same node values.

Example 1:

Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]

Example 2:

Input: root = [2,1,1]
Output: [[1]]

Example 3:

Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]

Constraints:

  • The number of the nodes in the tree will be in the range [1, 10^4]
  • -200 <= Node.val <= 200

题目链接:https://leetcode.com/problems/find-duplicate-subtrees/

题目大意:求完全相同的子树

题目分析:序列化枚举判断即可,向左加'l',向右加'r',遇空加'n',递归的时候将每个孩子都当作当前的子树根来看待,节点并不是根据其value值判相等,需要用一个map记录当前的序列化串出现的次数,为2时记一次答案即可

11ms,时间击败98.38%

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    HashMap<String, Integer> mp = new HashMap<>();
    
    public String dfs(TreeNode root, StringBuilder sb, List<TreeNode> ans) {
        if (root == null) {
            return "n";
        }
        sb.append(root.val);
        sb.append("l").append(dfs(root.left, new StringBuilder(""), ans));
        sb.append("r").append(dfs(root.right, new StringBuilder(""), ans));

        String cur = sb.toString();
        mp.put(cur, mp.getOrDefault(cur, 0) + 1);
        if (mp.get(cur) == 2) {
            ans.add(root);
        }
        return cur;
    }
    
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        List<TreeNode> ans = new ArrayList<>();
        dfs(root, new StringBuilder(""), ans);
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值