定义二叉树1:
代码如下:
class BinaryTree:
def __init__(self,nodeObj): #初始化
self.key = nodeObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode): #插入左子树
if not self.leftChild:
self.leftChild = BinaryTree(newNode)
else:
BinaryTree(newNode).leftChild = self.leftChild
self.leftChild = BinaryTree(newNode)
def inserRight(self,newNode): #插入右子树
if not self.rightChild:
self.rightChild = BinaryTree(newNode)
else:
BinaryTree(newNode).rightChild = self.rightChild
self.rightChild = BinaryTree(newNode)
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def getRootVal(self):
return self.key
def setRootVal(self,obj):
self.key = obj
r = BinaryTree('a')
print(r.getRightChild)
print(r.getLeftChild)
r.insertLeft('b')
print(r.getLeftChild()) #获得左子树地址
print(r.getLeftChild().getRootVal()) #获得左子树的值
r.inserRight('c')
print(r.getRightChild()) #获得右子树地址
print(r.getRightChild().getRootVal()) #获得右子树值
r.getRightChild().setRootVal('hello')
print(r.getRightChild().getRootVal())
运行结果为:
False
7
192:A_Primary cherish$ /usr/local/bin/python3.7 "/Users/cherish/Documents/学习3_Python/A_Primary/Arithmetic/Binary 2.py"
<bound method BinaryTree.getRightChild of <__main__.BinaryTree object at 0x101fad470>>
<bound method BinaryTree.getLeftChild of <__main__.BinaryTree object at 0x101fad470>>
<__main__.BinaryTree object at 0x101ebcf98>
b
<__main__.BinaryTree object at 0x101fad4a8>
c
hello
网友评论