Class TreeNode

class TreeNode:
def init(self, value):
self.value = value # Data
self.children = # References to other nodes

def dfs(root, target, path=()):
path = path + (root,)

if root.value == target:
    return path

for child in root.children:
    result = dfs(child, target, path)
    if result:
        return result

return None

Test code, do not remove

sample_root_node = TreeNode(“A”)
two = TreeNode(“B”)
three = TreeNode(“C”)
sample_root_node.children = [three, two]
four = TreeNode(“D”)
five = TreeNode(“E”)
six = TreeNode(“F”)
seven = TreeNode(“G”)
two.children = [five, four]
three.children = [seven, six]
path = dfs(sample_root_node, “G”)

if path:
node_values = [node.value for node in path]
print(node_values)
else:
print(“Target value not found.”)
Did you return the path if it isn’t None?
uyarısı ile karşılaştım ama çıktı olarak # [‘A’, ‘C’, ‘G’] aldım.
nerde hata yaptım anlayamadım

If you want path to be a tuple, you could do path=(,)
or you could do
path = None as the default parameter
and then

    if path is None:
      path = tuple()

in the function.

from TreeNode import TreeNode

def dfs(root, target, path=()):
if path is None:
path = tuple()

if root.value == target:
    return path

for child in root.children:
    result = dfs(child, target, path)
    if result:
        return result

return False  # veya [] gibi bir değer döndürerek hedef değeri bulamadığını belirtin

Test code, do not remove

sample_root_node = TreeNode(“A”)
two = TreeNode(“B”)
three = TreeNode(“C”)
sample_root_node.children = [three, two]
four = TreeNode(“D”)
five = TreeNode(“E”)
six = TreeNode(“F”)
seven = TreeNode(“G”)
two.children = [five, four]
three.children = [seven, six]
path = dfs(sample_root_node, “G”)
path = dfs(sample_root_node, “G”)
if path is False:
print(“Target value not found.”)
else:
print(path)

Target value not found.

ama sistem " Did you return the path if it isn’t None ?" uyarısı verdi