树(1)------实现和遍历

1、树的性质:

(1)树是分层的,分层的意思是树的顶层部分更加宽泛一般底层部分更加精细具体。

(2)一个节点(node)的所有子节点(children)和另一个节点的子节点是完全独立的。

(3)它的每个叶子节点(leaf)都是不同的。

2、相关概念:

节点、边、根节点、路径、父节点、兄弟节点、……

3、树的实现

(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]

r=BinaryTree('a')
insertLeft(r,'b')
insertRight(r,'c')
insertRight(r[1],'d')
insertLeft(r[2],'e')
insertRight(r[2],'f')
print(r)
I=getLeftChild(r)
print(I)

(2)节点和引用

class BinaryTree:
    def __init__(self,rootObi):
        self.key=rootObi
        self.leftChild=None
        self.rightChild=None
    def insertLeft(self,newNode):
        if self.leftChild==None:
            self.leftChild=BinaryTree(newNode)
        else:
            t=BinaryTree(newNode)
            t.leftChild=self.leftChild
            self.leftChild=t
    def insertRight(self,newNode):
        if self.rightChild==None:
            self.rightChild=BinaryTree(newNode)
        else:
            t=BinaryTree(newNode)
            t.rightChild=self.rightChild
            self.rightChild=t 
    def getRightChild(self):
        return self.rightChild
    def getLeftChild(self):
        return self.leftChild
    def setRootVal(self,obj):
        self.key=obj
    def getRootVal(self):
        return self.key

r=BinaryTree('a')
print(r.getRootVal())
print(r.getLeftChild())
r.insertLeft('b')
r.insertRight('c')
r.insertLeft('d')
r.insertRight('e')
print(r.getRootVal())
print(r.getLeftChild().getLeftChild().getRootVal())
print(r.getRightChild().getRightChild().getRootVal())

4、树的遍历

前序遍历:中,左,右

中序遍历:左,中,右

后序遍历:左,右,中

前序遍历:

扫描二维码关注公众号,回复: 891273 查看本文章
def preorder(tree):
    if tree:
        print(tree.getRootVal())
        preorder(tree.getLeftChild())
        preorder(tree.getRightChild())

#放入上面类中的代码
def preorder(self):
    print(self.key)
    if self.leftChild:
        self.leftChild.preorder()
    if self.RightChild:
        self.RightChild.preorder()

后序遍历:

def postorder(tree):
    if tree:
        postorder(tree.getLeftChild())
        postorder(tree.getRightChild())
        print(tree.getRootVal())

中序遍历:

def inorder(tree):    
    if tree:
        inorder(tree.getLeftChild())
        print(tree.getRootVal())
        inorder(tree.getRightChild())

 5、堆(最小堆、最大堆)

python模块:from pythonds.trees.binheap import BinHeap

猜你喜欢

转载自www.cnblogs.com/Lee-yl/p/9048081.html