DFS非递归

def DFS(root):
        # 非递归DFS
        '''
        利用栈完成非递归
        1 初始化根节点,标记为访问过,入栈
        2 取栈顶元素不出栈:
            如果该元素有未访问的邻接点,访问该邻接点,入栈,
            如果该元素所有邻接点都被访问或没有邻接点,出栈
        '''
        stack = [root]
        order = [root.val]
        visited = [root]
        while stack:

            if root:
                if  root.left and root.left not in visited:
                    root = root.left
                    stack.append(root)
                    order.append(root.val)
                    visited.append(root)
                elif  root.right and root.right not in visited:
                    root = root.right
                    stack.append(root)
                    order.append(root.val)
                    visited.append(root)

                else:
                    stack.pop()
                    if stack:
                        root = stack[-1]
        print(order)
        return order
def stringToTreeNode(input):
    input = input.strip()
    input = input[1:-1]
    if not input:
        return None

    inputValues = [s.strip() for s in input.split(',')]
    root = TreeNode(int(inputValues[0]))
    nodeQueue = [root]
    front = 0
    index = 1
    while index < len(inputValues):
        node = nodeQueue[front]
        front = front + 1

        item = inputValues[index]
        index = index + 1
        if item != "null":
            leftNumber = int(item)
            node.left = TreeNode(leftNumber)
            nodeQueue.append(node.left)

        if index >= len(inputValues):
            break

        item = inputValues[index]
        index = index + 1
        if item != "null":
            rightNumber = int(item)
            node.right = TreeNode(rightNumber)
            nodeQueue.append(node.right)
    return root


def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)

            root = stringToTreeNode(line)
            ret = Solution().rob(root)
            out = str(ret)
        except StopIteration:
            break


if __name__ == '__main__':
    main()

 

你可能感兴趣的:(数据结构与算法)