此DFS实施有什么问题?

时间:2019-10-15 14:17:40

标签: python depth-first-search

我不确定以下深度优先搜索代码有什么问题。预期与计划的输出将包括在最后。我通过运行来自geeksforgeeks的代码(对他们有/没有)获得了预期的输出。任何帮助,将不胜感激。 这是我的代码:

class Node:
    def __init__(self, val):
        self._val = val
        self._chdrn = []

class Nary:

    def __init__(self, n: int):
        self._n = n
        self._root = None

    def insert(self, val: int):
        nn = Node(val)
        if not self._root:
            self._root = nn
        else:
            def recur(parent: Node):
                print("Parent: ", parent._val)
                if len(parent._chdrn) < self._n:
                    parent._chdrn.append(nn)
                    return 1
                else:
                    for chdl in parent._chdrn:
                        ret = recur(chdl)
                        if ret == 1:
                            break
            parent = self._root
            recur(parent)

    def dfs(self):
        def _dfs(node: Node):
            if not node: return
            print(node._val, end=' ')
            for chld in node._chdrn:
                # print("current child = ", chld._val)
                _dfs(chld)
        _dfs(self._root)

Tree  = Nary(3)
for i in range(10): Tree.insert(i)
Tree.dfs()

预期输出:0 1 4 5 6 2 7 8 9 3
程序输出:0 1 4 7 8 9 5 6 2 7 8 9 3

1 个答案:

答案 0 :(得分:0)

您的DFS代码无所事事。用insert方法构造树是错误的。

recur中遍历子级时,需要以递归的方式返回。否则,同一节点将被插入多个父节点下。

class Node:
    def __init__(self, val):
        self._val = val
        self._chdrn = []


class Nary:

    def __init__(self, n: int):
        self._n = n
        self._root = None

    def insert(self, val: int):
        print(f"Inserting {val}")
        nn = Node(val)
        if not self._root:
            self._root = nn
        else:
            def recur(parent: Node):
                if len(parent._chdrn) < self._n:
                    print(f"Added under parent: {parent._val}")
                    parent._chdrn.append(nn)
                    return 1
                else:
                    for chdl in parent._chdrn:
                        ret = recur(chdl)
                        if ret == 1:
                            return 1  # not just break

            parent = self._root
            recur(parent)

    def dfs(self):
        def _dfs(node: Node):
            if not node: return
            print(node._val, end=' ')
            for chld in node._chdrn:
                # print("current child = ", chld._val)
                _dfs(chld)

        _dfs(self._root)


Tree = Nary(3)
for i in range(10): Tree.insert(i)
Tree.dfs()

此树的正确DFS顺序是:

0 1 4 7 8 9 5 6 2 3 

您应该绘制出树并手动执行DFS验证。