以下是一個示例實(shí)現(xiàn)Python中二叉樹的TreeNode類:
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_left(self, value):
if self.left is None:
self.left = TreeNode(value)
else:
new_node = TreeNode(value)
new_node.left = self.left
self.left = new_node
def insert_right(self, value):
if self.right is None:
self.right = TreeNode(value)
else:
new_node = TreeNode(value)
new_node.right = self.right
self.right = new_node
# 創(chuàng)建一個二叉樹
root = TreeNode(1)
root.insert_left(2)
root.insert_right(3)
root.left.insert_left(4)
root.left.insert_right(5)
root.right.insert_left(6)
root.right.insert_right(7)
# 遍歷二叉樹
def inorder_traversal(node):
if node:
inorder_traversal(node.left)
print(node.value)
inorder_traversal(node.right)
inorder_traversal(root)
在上面的示例中,我們定義了一個TreeNode類,其中包含節(jié)點(diǎn)的值以及左子節(jié)點(diǎn)和右子節(jié)點(diǎn)。我們還實(shí)現(xiàn)了insert_left()和insert_right()方法來插入左子節(jié)點(diǎn)和右子節(jié)點(diǎn)。最后,我們創(chuàng)建了一個二叉樹,并通過inorder_traversal()函數(shù)來進(jìn)行中序遍歷。