652. Find Duplicate Subtrees
use std::borrow::Borrow; use std::cell::RefCell; use std::collections; use std::collections::HashMap; use std::rc::Rc; /** 652. Find Duplicate Subtrees https://leetcode.com/problems/find-duplicate-subtrees/ 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: 1. The number of the nodes in the tree will be in the range [1, 10^4] 2. -200 <= Node.val <= 200 */ // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } pub struct Solution {} fn to_rc(root: &Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> { match root { Some(node) => Some(Rc::clone(node)), None => None } } impl Solution { /* solution: use tree traversal(post-order) to scan Tree, then use HaspMap to check if has duplicate node, Time:O(n), Space:O(n) */ pub fn find_duplicate_subtrees(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<Rc<RefCell<TreeNode>>>> { let mut result: Vec<Option<Rc<RefCell<TreeNode>>>> = Vec::new(); //HashMap: key is string, value is int let mut hashMap: HashMap<String, i32> = HashMap::new(); Self::post_order(root, &mut hashMap, &mut result); result } /** post_order: left->right->root */ fn post_order(root: Option<Rc<RefCell<TreeNode>>>, hashMap: &mut HashMap<String, i32>, result: &mut Vec<Option<Rc<RefCell<TreeNode>>>>) -> String { let copied = to_rc(&root); match root { Some(node) => { let left_str = Self::post_order(node.as_ref().borrow().left.clone(), hashMap, result); let right_str = Self::post_order(node.as_ref().borrow().right.clone(), hashMap, result); let mut val_ = String::new(); val_.push_str(node.as_ref().borrow().val.to_string().as_ref()); val_.push('_'); val_.push_str(left_str.as_ref()); val_.push('_'); val_.push_str(right_str.as_ref()); if *hashMap.get(&val_).unwrap_or(&0) == 1 { result.push(copied) } *hashMap.entry(val_.clone()).or_default() += 1; val_ } None => { "#".to_string() } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2021-02-21 设计模式-命令模式
2020-02-21 回溯算法(Backtracking)
2019-02-21 对于开发团队管理的理解