http://interactivepython.org/courselib/static/pythonds/index.html
Problem Solving with Algorithms and Data Structures
树
在计算机科学中有许多应用:
操作系统,数据库,计算机网络
文件系统
网页
- Vocabulary and Definitions
元素:
root,branches,leaves
特性:
hierarchical
在每个节点问一个问题,选择合适的答案的路径继续向下走
可以移动任意一个子树,不影响低层的结构
一个节点的children和另一个节点的children是独立的
因此在改变子节点的时候不会影响其他子节点
每个叶节点是唯一的
因此从根到叶节点有唯一的一条路径
概念:
node: name->key, additional information->payload
edge: 节点间的关系,一个节点只有一个incoming edge,有多个outgoing edge
root: 树里唯一一个没有incoming edge的节点
path,
children,parent,sibling,subtree
leaf node:没有children的node
level: 从root到节点的path中edge的个数
height: 这个树里最大的level
binary tree: 树里的每个节点都最多只有两个children
定义:
Definition One: A tree consists of a set of nodes and a set of edges that connect pairs of nodes.
Definition Two: A tree is either empty or consists of a root and zero or more subtrees, each of which is also a tree. The root of each subtree is connected to the root of the parent tree by an edge.
- List of Lists Representation
a tree represented by a list of lists
creating a simple tree using a list
myTree = ['a',['b',['d',[],[]],['e',[],[]]],['c',['f',[],[]],[]]]
print(myTree)
print('left subtree =',myTree[1])
print(myTree[1][1])
print(myTree[1][1][1])
每个list的第一个元素是root,第二个元素是left subtree,第三个元素是right subtree
叶节点有一个root和两个空的list
def BinaryTree(r):
return [r, [], []]
#to insert a left child
def insertLeft(root,newBranch):
t = root.pop(1) #1st level left subtree
if len(t) > 1: #if null, len is 0
root.insert(1,[newBranch,t,[]]) #insert newBranch in left position
else:
root.insert(1,[newBranch, [], []])
return root
r = BinaryTree(3)
print(r)
#[3, [], []]
print(len(r.pop(1)))
#0
insertLeft(r,4)
print(r)
#[3, [4, [], []]]
insertLeft(r,5)
print(r)
#[3, [5, [4, [], []], []]]
root = r
newBranch = 6
t = root.pop(1)
print(t)
#[5, [4, [], []], []]
print(len(t))
#3
root.insert(1,[newBranch,t,[]])
print(root)
#[3, [6, [5, [4, [], []], []], []]]
t = root.pop(1)
print(t)
#[6, [5, [4, [], []], []], []]
print(len(t))
#3
def BinaryTree(r):
return [r, [], []]
#to insert a left child
def insertLeft(root,newBranch):
t = root.pop(1) #1st level left subtree
if len(t) > 1: #if null, len is 0
root.insert(1,[newBranch,t,[]]) #insert newBranch in left position
else:
root.insert(1,[newBranch, [], []])
return root
r = BinaryTree(3)
insertLeft(r,4)
insertLeft(r,5)
def insertRight(root,newBranch):
t = root.pop(2)
if len(t)>1:
root.insert(2,[newBranch,[],t])
else:
root.insert(2,[newBranch,[],[]])
return root
insertRight(r,6)
print(r)
insertRight(r,7)
print(r)
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]
print(getLeftChild(r))
print(getRightChild(r))
print(getRightChild(getLeftChild(r)))
def getRootVal(root):
return root[0]
def setRootVal(root,newVal):
root[0] = newVal
return root[0]
print(getRootVal(r))
setRootVal(r,10)
print(getRootVal(r))