Java?C++?算法題解leetcode652尋找重復子樹
更新時間:2022年09月14日 09:34:56 作者:AnjaVon
這篇文章主要為大家介紹了Java?C++?算法題解leetcode652尋找重復子樹示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
題目要求


思路一:DFS+序列化
- 設計一種規(guī)則將所有子樹序列化,保證不同子樹的序列化字符串不同,相同子樹的序列化串相同。
- 用哈希表存所有的字符串,統(tǒng)計出現(xiàn)次數(shù)即可。
- 定義map中的關鍵字(
key)為子樹的序列化結果,值(value)為出現(xiàn)次數(shù)。
- 定義map中的關鍵字(
- 此處采用的方式是在DFS遍歷順序下的每個節(jié)點后添加"-",遇到空節(jié)點置當前位為空格。
Java
class Solution {
Map<String, Integer> map = new HashMap<>();
List<TreeNode> res = new ArrayList<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
DFS(root);
return res;
}
String DFS(TreeNode root) {
if (root == null)
return " ";
StringBuilder sb = new StringBuilder();
sb.append(root.val).append("-");
sb.append(DFS(root.left)).append(DFS(root.right));
String sub = sb.toString(); // 當前子樹
map.put(sub, map.getOrDefault(sub, 0) + 1);
if (map.get(sub) == 2) // ==保證統(tǒng)計所有且只記錄一次
res.add(root);
return sub;
}
}
- 時間復雜度:O(n^2)
- 空間復雜度:O(n)
C++
- 要把節(jié)點值轉換為字符串格式……嗚嗚嗚卡了半天才意識到
class Solution {
public:
unordered_map<string, int> map;
vector<TreeNode*> res;
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
DFS(root);
return res;
}
string DFS(TreeNode* root) {
if (root == nullptr)
return " ";
string sub = "";
sub += to_string(root->val); // 轉換為字符串?。?!
sub += "-";
sub += DFS(root->left);
sub += DFS(root->right);
if (map.count(sub))
map[sub]++;
else
map[sub] = 1;
if (map[sub] == 2) // ==保證統(tǒng)計所有且只記錄一次
res.emplace_back(root);
return sub;
}
};
- 時間復雜度:O(n^2)
- 空間復雜度:O(n)
Rust
- 在判定等于222的地方卡了好久,報錯
borrow of moved value sub,沒認真學rust導致閉包沒搞好,然后根據(jù)報錯內(nèi)容猜了下,把上面的加了個clone()果然好了。
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
impl Solution {
pub fn find_duplicate_subtrees(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<Rc<RefCell<TreeNode>>>> {
let mut res = Vec::new();
fn DFS(root: &Option<Rc<RefCell<TreeNode>>>, map: &mut HashMap<String, i32>, res: &mut Vec<Option<Rc<RefCell<TreeNode>>>>) -> String {
if root.is_none() {
return " ".to_string();
}
let sub = format!("{}-{}{}", root.as_ref().unwrap().borrow().val, DFS(&root.as_ref().unwrap().borrow().left, map, res), DFS(&root.as_ref().unwrap().borrow().right, map, res));
*map.entry(sub.clone()).or_insert(0) += 1;
if map[&sub] == 2 { // ==保證統(tǒng)計所有且只記錄一次
res.push(root.clone());
}
sub
}
DFS(&root, &mut HashMap::new(), &mut res);
res
}
}
- 時間復雜度:O(n^2)
- 空間復雜度:O(n)
思路二:DFS+三元組
- 和上面其實差不多,三元組本質上也是一種序列化形式,可以指代唯一的子樹結構:
- 三元組中的內(nèi)容為(根節(jié)點值,左子樹標識,右子樹標識)(根節(jié)點值, 左子樹標識,右子樹標識)(根節(jié)點值,左子樹標識,右子樹標識);
- 這個標識是給每個不同結構的子樹所賦予的唯一值,可用于標識其結構。
- 所以三元組相同則判定子樹結構相同;
- 該方法使用序號標識子樹結構,規(guī)避了思路一中越來越長的字符串,也減小了時間復雜度。
- 三元組中的內(nèi)容為(根節(jié)點值,左子樹標識,右子樹標識)(根節(jié)點值, 左子樹標識,右子樹標識)(根節(jié)點值,左子樹標識,右子樹標識);
- 定義哈希表mapmapmap存儲每種結構:
- 關鍵字為三元組的字符串形式,值為當前子樹的標識和出現(xiàn)次數(shù)所構成的數(shù)對。
- 其中標識用從000開始的整數(shù)flagflagflag表示。
Java
class Solution {
Map<String, Pair<Integer, Integer>> map = new HashMap<String, Pair<Integer, Integer>>();
List<TreeNode> res = new ArrayList<>();
int flag = 0;
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
DFS(root);
return res;
}
public int DFS(TreeNode root) {
if (root == null)
return 0;
int[] tri = {root.val, DFS(root.left), DFS(root.right)};
String sub = Arrays.toString(tri); // 當前子樹
if (map.containsKey(sub)) { // 已統(tǒng)計過
int key = map.get(sub).getKey();
int cnt = map.get(sub).getValue();
map.put(sub, new Pair<Integer, Integer>(key, ++cnt));
if (cnt == 2) // ==保證統(tǒng)計所有且只記錄一次
res.add(root);
return key;
}
else { // 首次出現(xiàn)
map.put(sub, new Pair<Integer, Integer>(++flag, 1));
return flag;
}
}
}
- 時間復雜度:O(n)
- 空間復雜度:O(n)
C++
class Solution {
public:
unordered_map<string, pair<int, int>> map;
vector<TreeNode*> res;
int flag = 0;
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
DFS(root);
return res;
}
int DFS(TreeNode* root) {
if (root == nullptr)
return 0;
string sub = to_string(root->val) + to_string(DFS(root->left)) + to_string(DFS(root->right)); // 當前子樹
if (auto cur = map.find(sub); cur != map.end()) { // 已統(tǒng)計過
int key = cur->second.first;
int cnt = cur->second.second;
map[sub] = {key, ++cnt};
if (cnt == 2) // ==保證統(tǒng)計所有且只記錄一次
res.emplace_back(root);
return key;
}
else { // 首次出現(xiàn)
map[sub] = {++flag, 1};
return flag;
}
}
};
- 時間復雜度:O(n)
- 空間復雜度:O(n)
Rust
- 三元組不好搞,所以用了兩個二元哈希表替代一個存放三元組和標識,另一個存放標識與出現(xiàn)次數(shù)。
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
impl Solution {
pub fn find_duplicate_subtrees(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<Rc<RefCell<TreeNode>>>> {
let mut res = Vec::new();
fn DFS(root: &Option<Rc<RefCell<TreeNode>>>, sub_flag: &mut HashMap<String, i32>, flag_cnt: &mut HashMap<i32, i32>, res: &mut Vec<Option<Rc<RefCell<TreeNode>>>>, flag: &mut i32) -> i32 {
if root.is_none() {
return 0;
}
let (lflag, rflag) = (DFS(&root.as_ref().unwrap().borrow().left, sub_flag, flag_cnt, res, flag), DFS(&root.as_ref().unwrap().borrow().right, sub_flag, flag_cnt, res, flag));
let sub = format!("{}{}{}", root.as_ref().unwrap().borrow().val, lflag, rflag);
if sub_flag.contains_key(&sub) { // 已統(tǒng)計過
let key = sub_flag[&sub];
let cnt = flag_cnt[&key] + 1;
flag_cnt.insert(key, cnt);
if cnt == 2 { // ==保證統(tǒng)計所有且只記錄一次
res.push(root.clone());
}
key
}
else { // 首次出現(xiàn)
*flag += 1;
sub_flag.insert(sub, *flag);
flag_cnt.insert(*flag, 1);
*flag
}
}
DFS(&root, &mut HashMap::new(), &mut HashMap::new(), &mut res, &mut 0);
res
}
}
- 時間復雜度:O(n)
- 空間復雜度:O(n)
總結
兩種方法本質上都是基于哈希表,記錄重復的子樹結構并統(tǒng)計個數(shù),在超過111時進行記錄,不過思路二更巧妙地將冗長的字符串變?yōu)槌?shù)級的標識符。
以上就是Java C++ 算法題解leetcode652尋找重復子樹的詳細內(nèi)容,更多關于Java C++ 尋找重復子樹的資料請關注腳本之家其它相關文章!
相關文章
C語言動態(tài)內(nèi)存泄露常見問題內(nèi)存分配改進方法詳解
今天遇見了一道有意思的內(nèi)存泄露題目,特地分享給大家,相信屏幕前的你學習完一定有所收獲,預祝讀者學習愉快,多多進步早日升職加薪2021-10-10
C++求1到n中1出現(xiàn)的次數(shù)以及數(shù)的二進制表示中1的個數(shù)
這篇文章主要介紹了C++求1到n中1出現(xiàn)的次數(shù)以及數(shù)的二進制表示中1的個數(shù),兩道基礎的算法題目,文中也給出了解題思路,需要的朋友可以參考下2016-02-02

