#建立一个二叉树
#声明一个二叉树节点类
#节点中包括:节点值,节点左子树根节点,节点右子树根节点,节点父节点
class TreeNode():
def __init__(self,value=None,leftNode=None,rightNode=None,parentNode=None):
self.val = value
self.leftnode = leftNode
self.rightnode = rightNode
self.parentnode = parentNode
def SetLeftNode(self,leftNode):
self.leftnode = leftNode
def SetRightNode(self,rightNode):
self.rightnode = rightNode
def SetParentNode(self,parentNode):
self.parentnode = parentNode
def GetLeftNode(self):
return self.leftnode
def GetRightNode(self):
return self.rightnode
def GetParentNode(self):
return self.parentnode
def GetValue(self):
return self.val
#定义根节点以及各个节点
root = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n6 = TreeNode(6)
n7 = TreeNode(7)
#设置根节点的左右节点
root.SetLeftNode(n2)
root.SetRightNode(n3)
#设置n2节点左右子树节点和其父节点
n2.SetLeftNode(n4)
n2.SetRightNode(n5)
n2.SetParentNode(root)
#设置n3节点左右子树节点和其父节点
n3.SetLeftNode(n6)
n3.SetRightNode(n7)
n3.SetParentNode(root)
#设置n4,n5节点的父节点
n4.SetParentNode(n2)
n5.SetParentNode(n2)
#设置n6,n7节点的父节点
n6.SetParentNode(n3)
n7.SetParentNode(n3)
#输出n2节点值,n2节点左孩子值,n2节点右孩子值,n2节点父节点值
print(str('n2 node value:')+str(n2.GetValue()))
print(str('n2 left child value:')+str(n2.GetLeftNode().GetValue()))
print(str('n2 right child value:')+str(n2.GetRightNode().GetValue()))
print(str('n2 parent node value:')+str(n2.GetParentNode().GetValue()))