一、树的定义
树有两种定义,一种涉及节点和边,另一种涉及递归。
1.定义一
树由节点及连接节点的边构成,树有以下属性:
(1)有一个根节点;
(2)除根节点外,其他每个节点都与其唯一的父节点相连;
(3)从根节点到其他每个节点都有且仅有一条路径;
(4).如果每个节点最多有两个子节点,我们就称这样的树为二叉树。
2.定义二
一棵树要么为空,要么由一个根节点和零棵或多棵子树构成,子树本身也是一棵树,每颗子树的根节点通过一条边练到父树的根节点。
二、树的Python代码实现
1.列表之列表实现
(1)实现方式如下:
def BinaryTree(r):
return [r, [], []]
def insertLeft(root, newBranch):
t = root.pop(1)
if len(t) > 1:
root.insert(1, [newBranch, t, []])
else:
root.insert(1, [newBranch, [], []])
return root
def insertRight(root, newBranch):
t = root.pop(2)
if len(t) > 1:
root.insert(2, [newBranch, [], t])
else:
root.insert(2, [newBranch, [], []])
return root
def getRootVal(root):
return root[0]
def setRootVal(root, newVal):
root[0] = newVal
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]
(2)测试例程如下:
r = BinaryTree(3)
insertLeft(r, 4)
insertLeft(r, 5)
insertRight(r, 6)
insertRight(r, 7)
l = getLeftChild(r)
setRootVal(l, 9)
2.节点与引用实现
(3)实现方式如下:
class BinaryTree:
def __init__(self, rootobj):
self.key = rootobj
self.leftChild = None
self.rightChild = None
def insertLeft(self, newNode):
if self.leftChild is None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self, newNode):
if self.rightChild is None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootVal(self, obj):
self.key = obj
def getRootVal(self):
return self.key
(4)测试例程如下:
r = BinaryTree('a')
r.insertLeft('b')
r.insertRight('c')
r.getLeftChild().insertLeft('d')
r.getLeftChild().insertRight('e')
r.getRightChild().insertLeft('f')