寻找重复的子树 Find Duplicate Subtrees
生活随笔
收集整理的這篇文章主要介紹了
寻找重复的子树 Find Duplicate Subtrees
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2018-07-29 17:42:29
問題描述:
問題求解:
本題是要求尋找一棵樹中的重復子樹,問題的難點在于如何在遍歷的時候對之前遍歷過的子樹進行描述和保存。
這里就需要使用之前使用過的二叉樹序列化的手法,將遍歷到的二叉樹進行序列化表達,我們知道序列化的二叉樹可以唯一的表示一棵二叉樹,并可以用來反序列化。
想到這里其實問題就已經解決了一大半了, 我們只需要在遍歷的過程中將每次的序列化結果保存到一個HashMap中,并對其進行計數,如果重復出現了,那么將當前的節點添加到res中即可。
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {List<TreeNode> res = new ArrayList<>();Map<String, Integer> map = new HashMap<>();helper(root, map, res);return res;}private String helper(TreeNode root, Map<String, Integer> map, List<TreeNode> res) {if (root == null) return "#";String str = root.val + "," + helper(root.left, map, res) + "," + helper(root.right, map, res);if (map.containsKey(str)) {if (map.get(str) == 1) res.add(root);map.put(str, map.get(str) + 1);}else map.put(str, 1);return str;}算法改進:
上述的算法基本可以在O(n)的時間復雜度解決問題,但是其中的字符串拼接是非常耗時的,這里可以對這個部分做出一點改進。如果我們不用序列化結果來表征一個子樹,用一個id值來表征的話,那么就可以規避掉字符串拼接的問題。
這里直接使用id的size來進行id的分配,值得注意的是由于已經給null分配了0,那么每次分配的大小應該是size + 1。
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {List<TreeNode> res = new ArrayList<>();Map<Long, Integer> id = new HashMap<>();Map<Integer, Integer> map = new HashMap<>();helper(root, id, map, res);return res;}private Integer helper(TreeNode root, Map<Long, Integer> id, Map<Integer, Integer> map, List<TreeNode> res) {if (root == null) return 0;Long key = ((long) root.val << 32) | helper(root.left, id, map, res) << 16 | helper(root.right, id, map, res);if (!id.containsKey(key)) id.put(key, id.size() + 1);int curId = id.get(key);if (map.containsKey(curId)) {if (map.get(curId) == 1) res.add(root);map.put(curId, map.get(curId) + 1);}else map.put(curId, 1);return curId;}?
轉載于:https://www.cnblogs.com/TIMHY/p/9386093.html
總結
以上是生活随笔為你收集整理的寻找重复的子树 Find Duplicate Subtrees的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数字转换为英文大写
- 下一篇: IOIOI卡片占卜(Atcoder-IO