摘要:文章目錄題目示例說(shuō)明限制解法一分析實(shí)現(xiàn)復(fù)雜度題目給定一棵二叉樹(shù)的根節(jié)點(diǎn),請(qǐng)返回所有的重復(fù)子樹(shù)。示例示例輸入輸出示例輸入輸出示例輸入輸出說(shuō)明來(lái)源力扣鏈接限制二叉樹(shù)中的節(jié)點(diǎn)數(shù)量在之間。
給定一棵二叉樹(shù)的根節(jié)點(diǎn),請(qǐng)返回所有的重復(fù)子樹(shù)。對(duì)于每一類(lèi)重復(fù)子樹(shù),你只需要返回其中任意一個(gè)的根節(jié)點(diǎn)即可。如果兩棵二叉樹(shù)擁有相同的結(jié)構(gòu)和節(jié)點(diǎn)值,則稱(chēng)這兩棵二叉樹(shù)是重復(fù)的。
示例 1 1 1 :
- 輸入:
root = [1, 2, 3, 4, null, 2, 4, null, null, 4]
- 輸出:
[[2, 4], [4]]
示例 2 2 2 :
- 輸入:
root = [2, 1, 1]
- 輸出:
[[1]]
示例 3 3 3 :
- 輸入:
root = [2, 2, 2, 3, null, 3, null]
- 輸出:
[[2, 3], [3]]
- 來(lái)源: 力扣(LeetCode)
- 鏈接: https://leetcode-cn.com/problems/find-duplicate-subtrees
- 二叉樹(shù)中的節(jié)點(diǎn)數(shù)量在 [ 1 , ? 1 0 4 ] [1,/textit{ }10^4] [1,?104] 之間;
-200 <= Node.val <= 200
。
想要正確解答本題,只需要知道如何給出二叉樹(shù)的某種唯一性表達(dá)即可,接下來(lái)首先獲得以給定二叉樹(shù)的所有節(jié)點(diǎn)為根節(jié)點(diǎn)的子二叉樹(shù)的表達(dá)形式,然后得到所有重復(fù)表達(dá)形式對(duì)應(yīng)子樹(shù)的根節(jié)點(diǎn)即可。
實(shí)際上,所謂給出二叉樹(shù)的某種唯一表達(dá)其實(shí)就是對(duì)二叉樹(shù)進(jìn)行序列化,而在【LeetCode 二叉樹(shù)專(zhuān)項(xiàng)】二叉樹(shù)的序列化與反序列化(297)中,我們給出了基于二叉樹(shù)深度優(yōu)先搜索(前序遍歷、后序遍歷)以及廣度優(yōu)先搜索實(shí)現(xiàn)的二叉樹(shù)序列化。
接下來(lái),需要確定就是具體采用哪種方式序列化。本題采用二叉樹(shù)的后序遍歷對(duì)給定二叉樹(shù)的所有子樹(shù)進(jìn)行序列化。
from json import dumpsfrom typing import Optional, List, Set, Dict, Unionclass TreeNode: def __init__(self, val=0, left: "TreeNode" = None, right: "TreeNode" = None): self.val = val self.left = left self.right = rightclass Solution: def _find_duplicate_subtrees(self, root: TreeNode, memorandum: Dict[str, int], results: List[TreeNode]) -> Optional[List[int]]: if not isinstance(root, TreeNode): return left = self._find_duplicate_subtrees(root.left, memorandum, results) right = self._find_duplicate_subtrees(root.right, memorandum, results) postorder = [] if left: postorder = postorder + left else: postorder.append(left) if right: postorder = postorder + right else: postorder.append(right) postorder.append(root.val) dumped = dumps(postorder) # if dumped in memorandum.keys() and memorandum[dumped] == 1: if memorandum.get(dumped, 0) == 1: # The above commented if-clause is a pedantic counterpart. results.append(root) memorandum[dumped] = memorandum.get(dumped, 0) + 1 return postorder def find_duplicate_subtrees(self, root: Optional[TreeNode]) -> Optional[List[TreeNode]]: if not isinstance(root, TreeNode): return memorandum = dict() results = [] self._find_duplicate_subtrees(root, memorandum, results) print("memorandum =", memorandum) return resultsdef postorder(root: TreeNode, tree: List[Union[int, None]]): if not root: tree.append(None) return postorder(root.left, tree) postorder(root.right, tree) tree.append(root.val)def main(): node7 = TreeNode(4) node6 = TreeNode(4) node5 = TreeNode(2, left=node7) node4 = TreeNode(4) node3 = TreeNode(3, node5, node6) node2 = TreeNode(2, left=node4) node1 = TreeNode(1, node2, node3) root = node1 sln = Solution() for root in sln.find_duplicate_subtrees(root): tree = [] postorder(root, tree) print("postorder =", dumps(tree))if __name__ == "__main__": main()
運(yùn)行上述解答的輸出結(jié)果為:
memorandum = {"[null, null, 4]": 3, "[null, null, 4, null, 2]": 2, "[null, null, 4, null, 2, null, null, 4, 3]": 1, "[null, null, 4, null, 2, null, null, 4, null, 2, null, null, 4, 3, 1]": 1}postorder = [null, null, 4]postorder = [null, null, 4, null, 2]
實(shí)際上, LeetCode 官方通過(guò)使用 collections
模塊中的 Counter
類(lèi),給出了一個(gè)如下的非常優(yōu)雅的解答,其中關(guān)于 Counter 類(lèi)的使用,可以參考【源碼共讀】Python 標(biāo)準(zhǔn)模塊 collections 中 Counter 類(lèi)詳解。
from typing import Optional, List, Dict, Unionfrom collections import Counterclass TreeNode: def __init__(self, val=0, left: "TreeNode" = None, right: "TreeNode" = None): self.val = val self.left = left self.right = rightclass Solution: def _collect(self, node: TreeNode, duplicates: List[TreeNode], count: Counter): if not node: return "#" serial = "{},{},{}".format(self._collect(node.left, duplicates, count), self._collect(node.right, duplicates, count), node.val) count[serial] += 1 if count[serial] == 2: duplicates.append(node) return serial def elegantly_find_duplicate_subtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: count = Counter() duplicates = [] self._collect(root, duplicates, count) return duplicatesdef postorder(root: TreeNode, tree: List[Union[int, None]]): if not root: tree.append(None) return postorder(root.left, tree) postorder(root.right, tree) tree.append(root.val)def main(): node7 = TreeNode(4) node6 = TreeNode(4) node5 = TreeNode(2, left=node7) node4 = TreeNode(4) node3 = TreeNode(3, node5, node6) node2 = TreeNode(2, left=node4) node1 = TreeNode(1, node2, node3) root = node1 sln = Solution() for root in sln.elegantly_find_duplicate_subtrees(root): tree = [] postorder(root, tree) print("postorder =", dumps(tree))if __name__ == "__main__": main()
實(shí)際上,在上述解答的 第 15 15 15 行中,如果將 return "#"
改為 return
也是正確的,但不為何此時(shí)在 LeetCode
上提交時(shí),執(zhí)行耗時(shí)和內(nèi)存消耗的數(shù)據(jù)都非常差,希望看到這篇題解而且知道緣由的有緣人可以在評(píng)論區(qū)留下你的指導(dǎo)。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/123340.html
摘要:對(duì)于同一類(lèi)的重復(fù)子樹(shù),你只需要返回其中任意一棵的根結(jié)點(diǎn)即可。兩棵樹(shù)重復(fù)是指它們具有相同的結(jié)構(gòu)以及相同的結(jié)點(diǎn)值。這里再用存儲(chǔ),鍵序列化結(jié)果,值樹(shù)節(jié)點(diǎn)組成的鏈表。 題目地址:https://leetcode-cn.com/probl...題目描述:給定一棵二叉樹(shù),返回所有重復(fù)的子樹(shù)。對(duì)于同一類(lèi)的重復(fù)子樹(shù),你只需要返回其中任意一棵的根結(jié)點(diǎn)即可。 兩棵樹(shù)重復(fù)是指它們具有相同的結(jié)構(gòu)以及相同的結(jié)點(diǎn)...
摘要:解法一中序遍歷分析由于給定了二叉搜索樹(shù),因此首先考慮中序遍歷,使用示例,我們先來(lái)分別看一下二叉搜索樹(shù)和累加樹(shù)中序遍歷的結(jié)果二叉搜索樹(shù)二叉累加樹(shù)。這里還是使用示例,我們?cè)賮?lái)觀察一下二叉搜索樹(shù)和累加樹(shù)中序遍歷的結(jié)果二叉搜索樹(shù)二叉累加樹(shù)。 ...
文章目錄 一、題目1、題目描述2、基礎(chǔ)框架3、原題鏈接 二、解題報(bào)告1、思路分析2、時(shí)間復(fù)雜度3、代碼詳解 三、本題小知識(shí)四、加群須知 一、題目 1、題目描述 ??給你一棵二叉搜索樹(shù),請(qǐng)按 中序遍歷 將其重新排列為一棵遞增順序搜索樹(shù),使樹(shù)中最左邊的節(jié)點(diǎn)成為樹(shù)的根節(jié)點(diǎn),并且每個(gè)節(jié)點(diǎn)沒(méi)有左子節(jié)點(diǎn),只有一個(gè)右子節(jié)點(diǎn)。??樣例輸入: [5,3,6,2,4,null,8,1,null,null,nu...
摘要:如果左右子樹(shù)返回的最低共同父節(jié)點(diǎn)值都不是空,說(shuō)明和分別位于的左右子樹(shù),那么就是最低共同父節(jié)點(diǎn)。 235題-題目要求 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of L...
閱讀 2664·2021-11-15 11:38
閱讀 2976·2021-11-02 14:44
閱讀 3934·2021-09-26 10:13
閱讀 3167·2021-08-13 15:02
閱讀 852·2019-08-30 15:56
閱讀 1628·2019-08-30 15:53
閱讀 2404·2019-08-30 13:01
閱讀 3293·2019-08-29 12:57