Leetcode 652. Find Duplicate Subtrees 尋找重複子樹 解題報告
阿新 • • 發佈:2019-02-10
這道題,給了一個二叉樹,然後需要找出所有重複的子樹(注意這個子樹返回一個就可以了)
做法naive一點可以記錄每個node的值,然後比較相同的值的遍歷。。
進階一點的話,可以記錄以每個節點為開始時的先序遍歷(中左右)的數值,然後遍歷的序列如果重複出現了,那麼就自然可以加入了
以上問題等價於:
記錄每一顆子樹的先序/後序便利結果,然後比較看有沒有重複的,有重複的就可以加入
PS:後續遍歷也可以,只要別讓root的順序在左右之間就好。。
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.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root, orders, res):
if root is None:
return '#END#'
# 前序,後續都可以
my_order = self.helper(root.left, orders, res)+'\t'+self.helper(root.right, orders, res)+"\t"+str(root.val)
# 只需要返回一個,所以只要再次出現一次就可以了,只返回第一個
if orders.get(my_order, 0 ) == 1:
res.append(root)
orders[my_order] = max(1, orders.get(my_order, 0) + 1)
return my_order
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
orders = dict()
res = list()
self.helper(root, orders, res)
return res