我寫了檢查代碼的特定值失敗兩棵樹是否同構與否:形狀同構代碼上
n = int(input())
parent1 = [int(item) for item in input().split()]
parent2 = [int(item) for item in input().split()]
#Structure to store information about nodes
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def add_child(self, node):
if not self.left:
self.left = node
elif not self.right:
self.right = node
def __repr__(self):
return 'TreeNode({self.data!r}, {self.left!r}, {self.right!r})'.format(self=self)
# Function which converts trees from parent array representation into the usual one.
def construct_tree(parents: list):
# Put Nodes with corresponding values into the list
constructed = [TreeNode(i) for i in range(len(parents))]
root = None
for i, parent in enumerate(parents):
# If parent's index = -1, it's the root of the tree
if parent == -1:
root = constructed[i]
else:
# Tie up current node to corresponding parent
constructed[parent].add_child(constructed[i])
return root
def are_isomorphic(T1, T2):
# Both roots are empty, trees are isomorphic by default
if len(parent1) != len(parent2):
return False
if T1 is None and T2 is None:
return True
#if T1.data != T2.data Gives the wrong answer
# If one of the trees is empty, and the other - isn't, do not bother to check further.
if T1 is None or T2 is None:
return False
# There are two possible cases for n1 and n2 to be isomorphic
# 1: The subtrees rooted at these nodes haven't been swapped
# 2: The subtrees rooted at these nodes have been swapped
return (are_isomorphic(T1.left, T2.left) and are_isomorphic(T1.right, T2.right) or
are_isomorphic(T1.left, T2.right) and are_isomorphic(T1.right, T2.left))
它給出了正確的答案几乎每一個樹對,除了這些:
樹節點(0,樹節點(1,樹節點(3,無,無),樹節點(4,無, 無)),樹節點(2,無,無))
樹節點(0,樹節點(1 ,TreeNode(3,None,None),None),TreeNode(2, TreeNode(4,None,None),None))
它們不是同構的,但我的代碼確定它們是。
我畫了這些樹,並認爲這種情況包含在遞歸過程中。 我嘗試這樣做:
if are_isomorphic(T1.left, T2.left) is False:
return "No"
if are_isomorphic(T1.left, T2.right) is False:
return "No"
if are_isomorphic(T1.right, T2.left) is False:
return "No"
if are_isomorphic(T1.right, T2.right) is False:
return "No"
else:
return "Yes"
這:
if (are_isomorphic(T1.left, T2.left) and are_isomorphic(T1.right, T2.right) is False):
return "No"
elif (are_isomorphic(T1.left, T2.right and are_isomorphic(T1.right, T2.left)) is False):
return "No"
else:
return "Yes"
有人可以解釋我缺少什麼?
該函數沒有定義「parent1」或「parent2」。另外,你的'__len__'函數是如何實現的?它可能是造成這個問題的原因。 –
'parent1'和'parent2'是treesm的父數組,它們是從控制檯輸入的。我沒有從父數組中包含代碼構建樹,因爲它正常工作並且與問題無關。 len()是一個內置的python函數。 – TheDoctor
是的,但它是什麼測量? '[3,None,None]'與[1,2,None]具有相同的長度。 –