Binary Tree -- 二叉树
本文记录二叉树的python语言实现:
基于List和class的实现
一、基于List 实现
# 用列表实现二叉树 [[root],[left-tree],[right-tree]]
def Binary_tree(root:any) -> list:
return [root,[],[]]
def insertLeft(root:list, newBranch:list) -> list:
left = root.pop(1)
if len(left) > 1: # 若原二叉树中存在左子树,插入后的左子树作为原左子树的父节点
root.insert(1,[newBranch, left, []])
else :
root.insert(1,[newBranch, [], []])
return root
def insertRight(root:list, newBranch:list) -> list:
right = root.pop(2)
if len(right) > 1:
root.insert(2,[newBranch,[],right])
else :
root.insert(2,[newBranch,[],[]])
return root
def getRootVal(root:list) -> any:
return root[0]
def setRootVal(root:list, newVal:any) -> None:
root[0] = newVal
def getLeftChild(root:list) -> any:
return root[1]
def getRightChild(root:list) -> any:
return root[2]
二、基于class的实现
class Binarytree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = Binarytree(newNode)
else : # 当插入前tree中存在左子树,那需让原左子树下调一层
left = Binarytree(newNode)
left.leftChild = self.leftChild
self.leftChild = left
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = Binarytree(newNode)
else :
right = Binarytree(newNode)
right.rightChild = self.rightChild
self.rightChild = right
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj:any):
self.key = obj
def getRootVal(self):
return self.key
# 两种class内遍历方法还未测试
# 前序遍历的class内实现
def preorder(self):
print(self.key)
if self.leftChild() != None:
self.leftChild.preorder()
if self.rightChild() != None:
self.rightChild.preorder()
# 中序遍历的class内实现
def inorder(self):
if self.leftChild() != None:
self.leftChild.inorder()
print(self.key)
if self.rightChild() != None:
self.rightChild.inorder()