📅  最后修改于: 2023-12-03 15:40:27.107000             🧑  作者: Mango
在计算机科学中,栈(stack)和树(tree)是两个重要的数据结构。尽管它们都能被表示为一组节点和指向它们的指针,但它们之间存在许多差异。下面是栈和树的区别:
栈是一种特殊的数据结构,它基本上是一个“先进后出”的容器,只能在顶部插入和删除元素。最后插入的元素将被首先删除。
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
树也是一种由节点和指针组成的数据结构,可以很好地模拟现实生活中的树形结构。
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
class BinaryTree:
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(tree.root, "")
elif traversal_type == "inorder":
return self.inorder_print(tree.root, "")
elif traversal_type == "postorder":
return self.postorder_print(tree.root, "")
def preorder_print(self, start, traversal):
if start:
traversal += (str(start.data) + "-")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def inorder_print(self, start, traversal):
if start:
traversal = self.inorder_print(start.left, traversal)
traversal += (str(start.data) + "-")
traversal = self.inorder_print(start.right, traversal)
return traversal
def postorder_print(self, start, traversal):
if start:
traversal = self.postorder_print(start.left, traversal)
traversal = self.postorder_print(start.right, traversal)
traversal += (str(start.data) + "-")
return traversal
# 实例化一棵二叉树
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
print("Pre-order Traversal: ", tree.print_tree("preorder"))
print("In-order Traversal: ", tree.print_tree("inorder"))
print("Post-order Traversal: ", tree.print_tree("postorder"))