652-Find Duplicate Subtrees
Description
Given 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 same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4
The following are two duplicate subtrees:
2
/
4
and
4
Therefore, you need to return above trees’ root in the form of a list.
問題描述
給定二叉樹, 返回所有重複子樹。對於每類重複子樹, 只需要返回任意一個子樹的根節點。
兩棵樹如何結構相同且所有對應節點的值相等, 那麼這兩棵樹重複。
問題分析
後序遍歷, 通過字串表示一棵樹, 通過map儲存字串對應個數, 若個數大於1, 說明此樹重複, 可以新增入結果中
解法
class Solution {
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
HashMap<String, Integer> map = new HashMap();
List<TreeNode> res = new ArrayList();
helper(root, map, res);
return res;
}
private String helper(TreeNode root, HashMap<String, Integer> map, List<TreeNode> res){
if(root == null) return "#";
String temp = root.val + helper(root.left, map, res) + helper(root.right, map, res);
if(!map.containsKey(temp)){
map.put(temp,1);
}else{
if(map.get(temp) < 2){
map.put(temp, 2);
res.add(root);
}
}
return temp;
}
}
相關文章
- [LeetCode] Find the Duplicate NumberLeetCode
- yum error - package is a duplicate withErrorPackage
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- DATAGUARD手記(DUPLICATE)(四)
- RMAN Duplicate RAC to Single Instance
- on duplicate key update簡單使用
- Handling duplicate form submission in Spring MVCORMSpringMVC
- Tensorboard: ValueError: Duplicate plugins for name projectorORBErrorPluginProject
- leetcode 219. Contains Duplicate IILeetCodeAI
- 錯誤:duplicate column name: picstitle
- rman duplicate操作手冊
- MySQL_插入更新 ON DUPLICATE KEY UPDATEMySql
- ERROR 1062 (23000): Duplicate entry for key 'PRIMARY'Error
- MySQL insert on duplicate key update 死鎖MySql
- Oracle rman duplicate遷移測試Oracle
- Oracle 11GR2 Duplicate from BackupOracle
- 解決 Inkscape 報錯 Duplicate 問題
- Remove Duplicate Letters 刪除重複元素REM
- ios-Multiple commands produced error xcode 10 [duplicate]iOSErrorXCode
- BUG: pymysql executemany不支援insert on duplicate key updateMySql
- DG:11.2.0.4 RAC線上duplicate恢復DG
- Cisdem Duplicate Finder for Mac:智慧管理你的檔案Mac
- MySQL 關於 INSERT INTO...ON DUPLICATE KEY UPDATE 的使用MySql
- 解決tensorboard報錯ValueError: Duplicate plugins for name projectorORBErrorPluginProject
- Advanced Duplicate Cleaner for mac - 智慧重複檔案清理Mac
- Oracle 如何快速的 duplicate 一個資料庫Oracle資料庫
- Duplicate Photos Fixer Pro for Mac(重複圖片清理)Mac
- Duplicate Detective for Mac(重複檔案檢測工具)Mac
- [vue-router] Duplicate named routes definition: { name: "home", path: "/home" }Vue
- 重複照片清理軟體:Duplicate Photos Fixer Pro for MacMac
- MYSQL報1022錯誤:Can't write;duplicate key in table '.....'MySql
- 重複照片清理軟體:Duplicate Photos Fixer Pro MacMac
- mysql實現merge功能之DUPLICATE key UPDATE語法MySql
- Java中List集合轉Map集合報錯:Duplicate keyJava
- DUMP-CX_SY_OPEN_SQL_DB-DBSQL_DUPLICATE_KEY_ERRORSQLError
- Duplicate Photos Fixer Pro for Mac重複照片清理軟體Mac
- oracle 19c dg搭建duplicate過程中報錯Oracle