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() } } } }