利用栈(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

得解!

posted @ 2020-05-12 09:17  Geeksongs  阅读(1956)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.