python 算法与数据结构 二叉树

二叉树类

class BiTNode:
    def __init__(self):
        self.data = None
        self.lchild = None
        self.rchild = None

将有序数组存为二叉树

def array2tree(arr,start,end): # 有序列表转二叉树
    root = None
    if end >= start:
        root = BiTNode()
        mid = (start+end+1)//2
        root.data = arr[mid]
        root.lchild = array2tree(arr, start, mid-1)
        root.rchild = array2tree(arr, mid+1, end)
    else:
        root = None
    return root

遍历打印二叉树(前序、中序、后序、层次)

def printName(func): # 装饰器,用来输出当前函数的函数名
    def warpper(*args,**kw):
        print(func.__name__)
        func(*args,**kw)
        print('--end--')
    return warpper        

@printName
def printTreeMidOrder(root): # 中序打印二叉树
    def _printTreeMidOrder(root): # 装饰器装饰递归函数通用做法
        if root == None:
            return
        if root.lchild != None:
            _printTreeMidOrder(root.lchild)
        print(root.data, end=' ')
        if root.rchild != None:
            _printTreeMidOrder(root.rchild)
    return _printTreeMidOrder(root)

@printName
def printTreePreOrder(root): # 前序打印二叉树
    def _printTreePreOrder(root):
        if root == None:
            return
        print(root.data, end=' ')
        if root.lchild != None:
            _printTreePreOrder(root.lchild)
        if root.rchild != None:
            _printTreePreOrder(root.rchild)
    return _printTreePreOrder(root)
  
@printName    
def printTreePostOrder(root): # 后序打印二叉树
    def _printTreePostOrder(root):
        if root == None:
            return
        if root.lchild != None:
            _printTreePostOrder(root.lchild)
        if root.rchild != None:
            _printTreePostOrder(root.rchild)
        print(root.data, end=' ')
    return _printTreePostOrder(root)
   
from collections import deque # 层次遍历需要用到队列
@printName
def printTreeLayer(root): # 层次遍历二叉树
    if root == None:
        return
    queue = deque()
    queue.append(root)
    while len(queue) > 0:
        p = queue.popleft()
        print(p.data, end=' ')
        if p.lchild:
            queue.append(p.lchild)
        if p.rchild:
            queue.append(p.rchild)
            
if __name__ == "__main__":
    mylist = [i for i in range(1, 11)]
    root = array2tree(mylist, 0, len(mylist)-1)
    print(mylist)
    printTreePreOrder(root)
    printTreeMidOrder(root)
    printTreePostOrder(root)
    printTreeLayer(root)

输出结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
printTreePreOrder
6 3 2 1 5 4 9 8 7 10 --end–
printTreeMidOrder
1 2 3 4 5 6 7 8 9 10 --end–
printTreePostOrder
1 2 4 5 3 7 8 10 9 6 --end–
printTreeLayer
6 3 9 2 5 8 10 1 4 7 --end–

猜你喜欢

转载自blog.csdn.net/qq_36936510/article/details/105590959