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

    得解!

  • 相关阅读:
    reduce()、filter()、map()、some()、every()、...展开属性
    react的this.setState详细介绍
    HDU
    The 2015 ACM-ICPC Asia Beijing Regional Contest
    Ubuntu 14.04 安装 WPScan
    蓝桥杯-历届试题-公式求值
    Ubuntu下快速搭建ACdream Online Judge v1.5.3
    Codeforces Round #290 (Div. 2)
    SOJ
    SOJ
  • 原文地址:https://www.cnblogs.com/geeksongs/p/12874186.html
Copyright © 2011-2022 走看看