树的结构如下所示:
我们使用深度优先搜索对其进行遍历:
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
得解!
原文:https://www.cnblogs.com/geeksongs/p/12874186.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!