本節我們將用Python實現樹結構中最簡單的二叉樹,并將在以后的章節中應用它。
二叉樹類
#二叉樹類
class BinaryTree(object):
# 初始化,傳入根節點的值
def __init__(self, root_value):
self.root = root_value
self.leftchild = None
self.rightchild = None
# 插入左子樹
def insert_left(self, left_value):
if self.leftchild == None :
self.leftchild = BinaryTree(left_value)
else:
left_subtree = BinaryTree(left_value)
left_subtree.leftchild = self.leftchild
self.leftchild = left_subtree
# 插入右子樹
def insert_right(self, right_value):
if self.rightchild == None :
self.rightchild = BinaryTree(right_value)
else:
right_subtree = BinaryTree(right_value)
right_subtree.rightchild = self.rightchild
self.rightchild = rightchild
# 設置根節點的值
def set_root(self, root_value):
self.root = root_value
# 獲取根節點的值
def get_root(self):
return self.root
# 獲取左子樹
def get_leftchild(self):
return self.leftchild
# 獲取右子樹
def get_rightchile(self):
return self.rightchild
二叉樹的遍歷
# 前序遍歷二叉樹
def pre_traversal(tree):
if tree != None:
print(tree.root)
pre_traversal(tree.leftchild)
pre_traversal(tree.rightchild)
# 中序遍歷二叉樹
def in_traversal(tree):
if tree != None:
in_traversal(tree.leftchild)
print(tree.root)
in_traversal(tree.rightchild)
# 后序遍歷二叉樹
def post_traversal(tree):
if tree != None:
post_traversal(tree.leftchild)
post_traversal(tree.rightchild)
print(tree.root)