zoukankan      html  css  js  c++  java
  • 利用栈(Stack)实现树(tree)的深度优先搜索(Python)

    树的结构如下所示:

     我们使用深度优先搜索对其进行遍历:

    class Node:
        def __init__(self, id, anime):
            self.id = id
            self.anime = anime
            self.left = None # <Left node>
            self.right = None # <Right node>
    
    
    
    def DFS_iterative(node):
        # Set up a list called nodes_list with `node` being the first and only entry.
        nodes_list=[node]
        while True:
            # If there are no entries in nodes_list, break.
            if len(nodes_list) == 0:
                break
            
            # node = last node in nodes_list.
            node = nodes_list[-1]
            # Remove the last node in nodes_list using slicing or list.pop().
            nodes_list.pop()
            # Print out the node's anime string.
            print(node.anime)
            # If node has a right node, append it to nodes_list.
            if node.right:
                nodes_list.append(node.right)
            # If node has a left node, append it to nodes_list.
            if node.left:
                nodes_list.append(node.left)
    # Create the nodes
    root = Node(1, "Code Geass")
    
    # Link up the nodes
    root.left = Node(2, "Steins Gate")
    root.right = Node(3, "Kimi no na wa")
    
    root.left.left = Node(4, "Death Note")
    root.left.right = Node(5, "Naruto")
    
    root.right.left = Node(6, "One Piece")
    root.right.right = Node(7, "Shingeki no Kyojin")
    
    DFS_iterative(root)

    输出:

    Code Geass
    Steins Gate
    Death Note
    Naruto
    Kimi no na wa
    One Piece
    Shingeki no Kyojin

    得解!

  • 相关阅读:
    Lazarus教程 中文版后续给出
    QBASIC教程
    Object Pascal中文手册 经典教程
    Pascal 基础教程
    Delphi中的关键字与保留字
    Pascal数据结构与算法
    Pascal小游戏 贪吃蛇
    Pascal小游戏 俄罗斯方块怀旧版
    Pascal ASCII和文本的转换
    IDEA安装问题解决
  • 原文地址:https://www.cnblogs.com/geeksongs/p/12874186.html
Copyright © 2011-2022 走看看