LeetCode每日一题(Find Duplicate Subtrees)

给定一棵二叉树的根节点,返回所有重复的子树。两棵树被认为是重复的,如果它们具有相同的结构和相同的节点值。例如,输入为根节点值为 [1,2,3,4,null,2,4,null,null,4] 的二叉树,输出为 [[2,4],[4]]。题目要求遍历整个树,记录已出现的子树,当遇到已出现一次的子树时,将其添加到答案数组中。" 115984466,10537499,MATLAB实现约束最小二乘法FIR滤波器设计,"['MATLAB编程', '数字滤波器', '信号处理', 'FIR滤波器设计', '约束优化']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

traversal 整个 tree, 同时记录已经出现的 subtree, 如果当前的 subtree 已经出现过且出现次数为**1 次**, 则把当前的这个 subtree 放到答案数组中。

严格来说这题对于不同语言可能复杂程度会有所差异,因为用数组或者切片直接作为 map 的 key, 不是所有语言都直接支持。


代码实现(Rust):

use std::collections::HashMap;
impl Solution {
    fn find(root: &Option<Rc<RefCell<TreeNode>>>, counts: &mut HashMap<Vec<i32>, i32>, ans: &mut Vec<Option<Rc<RefCell<TreeNode>>>>) -> Vec<i32> {
        if let Some(node) = root {
            let mut left = Solution::find(&node.borrow().left, counts, ans);
            let right = Solution::find(&node.borrow().right, counts, ans);
            left.extend(right);
            left.push(node.borrow().val);
            *counts.entry(left.clone()).or_insert(0) += 1;
            if counts.get(&left).unwrap() == &2 {
                ans.push(Some(node.clone()));
            }
            return left;
        }
        vec![-201]
    }

    pub fn find_duplicate_subtrees(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<Rc<RefCell<TreeNode>>>> {
        let mut counts = HashMap::new();
        let mut ans = Vec::new();
        Solution::find(&root, &mut counts, &mut ans);
        ans
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值