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

得解!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM