Python数据结构之二叉树(涵盖了构建、删除、查找、字典转换、非递归与递归遍历等)

MyTree.py

#coding=utf-8
import math

class BinTree:
    def __init__(self):
        self.root=None

    def is_empty(self):
        return self.root is None

    def get_root(self):
        return self.root

    def get_left(self):
        return self.root.left

    def get_right(self):
        return self.root.right

    def set_root(self,rootNode):
        self.root=rootNode

    def set_left(self,left):
        self.root.left=left

    def set_right(self,right):
        self.root.right=right

    def list_all(self,method):
        dic=[]
        dic=self.__list(method,self.root,dic)
        return dic



    def __list(self,method,Node,dic):
        if method=='before':
            dic.append(Node.data)
            if Node.left!=None:
                self.__list(method,Node.left,dic)
            if Node.right!=None:
                self.__list(method,Node.right,dic)
        elif method=='mid':
            if Node.left!=None:
                self.__list(method,Node.left,dic)
            dic.append(Node.data)
            if Node.right!=None:
                self.__list(method,Node.right,dic)
        else:
            if Node.left!=None:
                self.__list(method,Node.left,dic)
            if Node.right!=None:
                self.__list(method,Node.right,dic)
            dic.append(Node.data)
        return dic

    def get_Parent(self,Node):
        dic=[]
        Parent=self.__get_Parent(self.root,Node,dic)
        if len(Parent)>=1:
            Parent=Parent[0]
        else:
            Parent="error"
        return Parent

    def __get_Parent(self,Node,node,dic):
        if Node.left!=None  and Node.left.data==node:
            Parent=Node
            dic.append(Parent)
        if Node.right!=None  and Node.right.data==node:
            Parent=Node
        if Node.left!=None:
            Parent=self.__get_Parent(Node.left,node,dic)
        if Node.right!=None:
            Parent=self.__get_Parent(Node.right,node,dic)
        return dic

    def get_Brother(self,Node):
        dic=[]
        Parent=self.__get_Parent(self.root,Node,dic)
        if len(Parent)>=1:
            Parent=Parent[0]
            if Parent.left.data==Node:
                if Parent.right!=None:
                    return Parent.right.data
                else:
                    return "single kid, No Brothers"
            else:
                if Parent.left!=None:
                    return Parent.left.data
                else:
                    return "single kid, No Brothers"
        else:
            return "error"


    def get_width(self,num):
        dic=[]
        elems=self.__GBDepth(self.root,0,num,dic)
        width={len(elems):elems}
        return width

    def get_nodes_num(self):
        depth=self.get_Depth()
        nums=0
        for i in range(1,depth+1):
            dic=[]
            elems=self.__GBDepth(self.root,0,i,dic)
            #print elems
            nums+=len(elems)
        return nums

    def get_ByDepth(self,num):
        dic=[]
        elems=self.__GBDepth(self.root,0,num,dic)
        return elems

    def __GBDepth(self,Node,k,num,dic):
        k+=1
        if k<num:
            if Node.left!=None:
                self.__GBDepth(Node.left,k,num,dic)
            if Node.right!=None:
                self.__GBDepth(Node.right,k,num,dic)
        else:
            dic.append(Node.data)
        return dic

    def get_Depth(self):
        depth=self.__Depth(self.root,0)
        self.depth=depth
        return self.depth

    def __Depth(self,Node,k):
        k+=1
        if Node.left!=None and Node.right!=None:
            depth=max(self.__Depth(Node.left,k),self.__Depth(Node.right,k))
        elif Node.left!=None and Node.right==None:
            depth=self.__Depth(Node.left,k)
        elif Node.left==None and Node.right!=None:
            depth=self.__Depth(Node.right,k)
        else: 
            depth=k
        return depth

    def trans_Dict(self):
        dic=self.__Dict(self.root)
        #dic={self.root.data:dic}
        return dic

    def __Dict(self,Node):
        dic={}
        dic['value']=Node.data
        if Node.left!=None and Node.right!=None:
            dic['left']=self.__Dict(Node.left)
            dic['right']=self.__Dict(Node.right)
        elif Node.left!=None and Node.right==None:
            dic['left']=self.__Dict(Node.left)
        elif Node.left==None and Node.right!=None:
            dic['right']=self.__Dict(Node.right)
        else:
            dic={} 
            dic['value']=Node.data
        return dic

    def createByDict(self,Dict):
        Node=TreeNode(0)
        Node=self.__createByDict(Dict,Node)
        self.set_root(Node)
        return self.trans_Dict()

    def __createByDict(self,Dict,Node):
        if isinstance(Dict, dict):
            Node.data=Dict['value']
            if 'left' in Dict.keys():     
                Node.left=TreeNode(0)
                self.__createByDict(Dict['left'],Node.left)
            if 'right'  in Dict.keys():  
                Node.right=TreeNode(0)
                self.__createByDict(Dict['right'],Node.right)
        return Node

    def genelizeTZList(self):
        depth=self.get_Depth()
        List=['*' for i in range(pow(2,depth)-1)] 
        List=self.__genelizeTZList(self.root,List,0,0)
        return List

    def __genelizeTZList(self,Node,List,k,w):
        k+=1
        ww=w
        #print k,Node.data,w
        List[pow(2,k-1)-1+w]=Node.data
        if Node.left!=None:
            w=ww*2
            self.__genelizeTZList(Node.left,List,k,w)
        if Node.right!=None:
            w=ww*2+1
            self.__genelizeTZList(Node.right,List,k,w)
        return List


    def createByTZList(self,List):
        Nodes=[]
        for i in range(len(List)):
            if List[i]!='*':
                Nodes.append(TreeNode(List[i]))
            else:
                Nodes.append('*') 
        for j in range(len(List)):
            i=len(List)-j
            if i==len(List):
                pass
            elif List[i]!='*':
                #找到i的层数
                depth=int(math.log(i+1,2))
                num=int(math.ceil(1.0*(i+2-pow(2,depth))/2)-1)
                direct=(i+2-pow(2,depth))%2
                k=pow(2,depth-1)+num-1
                if direct==1:
                    #右节点
                    Nodes[k].left=Nodes[i]
                else:
                    Nodes[k].right=Nodes[i]
                #print List[i],List[k],depth-1,num,k
        self.set_root(Nodes[0])
        return self.trans_Dict()

    def list_all_UN(self,method):
        lis=[]
        res=[]
        if method=='before':
            Node=self.root
            lis.append(Node)
            #好厉害 此类问题的思考方式 先思考最简单的情况 再发散
            while(lis):
                node=lis[-1]
                lis=lis[:-1]
                if node:
                    res.append(node.data)
                if node.right:
                    lis.append(node.right)
                if node.left:
                    lis.append(node.left)     
        elif method=='mid':
            node = self.root  
            while lis or node:  
                while node:  
                    lis.append(node)  
                    node = node.left
                if len(lis)>0:
                    node = lis[-1]
                    lis=lis[:-1]
                    if node:
                        res.append(node.data)  
                    node= node.right 
        else:
            node = self.root
            lis.append(node)
            lis2=[]
            while lis :
                node=lis[-1]
                lis=lis[:-1]
                lis2.append(node)
                if node.left:
                    lis.append(node.left)
                if node.right:
                    lis.append(node.right)
            while lis2:
                value=lis2.pop().data
                if value:
                    res.append(value) 
        return res

    def list_layer(self):
        lis=[]
        res=[]
        lis.append(self.root)
        while lis:
            node=lis[0]
            #print node.data
            res.append(node.data)
            lis=lis[1:]
            if node.left:
                lis.append(node.left)
            if node.right:
                lis.append(node.right)
        return res

    def createBySortList(self,method1,method2,SortList1,SortList2):
        if method1=='before' and method2=='mid':
            Node=TreeNode(SortList1[0])
        elif method1=='after' and method2=='mid':
            Node=TreeNode(SortList1[-1])
        else:
            return 'only support begin-mid and after-mid'
        Node=self.__createBySortList(method1,method2,SortList1,SortList2,Node)
        self.set_root(Node)
        return self.trans_Dict()

    def __createBySortList(self,method1,method2,SortList1,SortList2,Node):
        if method1=='before' and method2=='mid':
            devide=SortList2.index(SortList1[0])
        else:
            devide=SortList2.index(SortList1[-1])
        Left2=SortList2[0:devide]
        Right2=SortList2[devide+1:len(SortList2)]
        Left1=[]
        Right1=[]
        for i in  SortList1:
            if i in Left2:
                Left1.append(i)
            if i in Right2:
                Right1.append(i)
        if len(Left1)>=1:
            if method1=='before' and method2=='mid':
                Node.left=TreeNode(Left1[0])
            else:
                Node.left=TreeNode(Left1[-1])
            self.__createBySortList(method1,method2,Left1,Left2,Node.left)
        if len(Right1)>=1:
            if method1=='before' and method2=='mid':
                Node.right=TreeNode(Right1[0])
            else:
                Node.right=TreeNode(Right1[-1])
            self.__createBySortList(method1,method2,Right1,Right2,Node.right)
        return Node

class TreeNode:
    def __init__(self,data):
        self.data=data
        self.left=None
        self.right=None
    def get_left(self):
        return self.left
    def get_right(self):
        return self.right
    def setParent(self,Node):
        self.parent=Node
    def setBrother(self,Node):
        self.brother=Node
    def isNone(self):
        if self.left!=None or self.right!=None:
            return True
        else:
            return False

test.py

#coding=utf-8
from MyTree import BinTree,TreeNode
import math
#子节点表示的 节点生成的构造法
a=[1,2,3,4,5,6]
print a.index(3),a[0:2],a[3:6],a[-2]
tree=BinTree()
node1=TreeNode(1)
node2=TreeNode(2)
node21=TreeNode(3)
node2.left=node21
node21.left=TreeNode(4)
node21.right=TreeNode(7)
node3=TreeNode(5)
node31=TreeNode(6)
node3.right=TreeNode(100)
node3.left=node31
node4=TreeNode(12)
node31.left=node4
node4.left=TreeNode(14)
node4.right=TreeNode(11)
#node31.right.right=TreeNode(6)
node1.left=node2
node1.right=node3
#node32=TreeNode(6)
#node3.right=node32
#node32.right=TreeNode(6)
tree.set_root(node1)
print tree.get_left().data
print tree.get_right().data
print tree.get_Depth()
print tree.get_ByDepth(4)
print tree.get_width(5)
print tree.trans_Dict()
print tree.list_all('before')
print tree.list_all('mid')
print tree.list_all('after')
print tree.list_all_UN('after')
print tree.list_layer()
''' List=[0,1,2,3,'*','*',5]
print tree.createByTZList(List)
#print tree.get_Depth()
dict1={'right': {'right': {'value': 5}, 'value': 2, 'left': {'value': 4}}, 'value': 0, 'left': {'value': 1, 'left': {'value': 3}}}
dict2=tree.createByTZList(List)
tree.createByDict(dict2)
print tree.get_ByDepth(3)
print tree.genelizeTZList()
before=[1, 2, 3, 4, 5, 100, 6, 12, 14]
mid=[4, 3, 2, 1, 100, 5, 6, 14, 12]
after=[4, 3, 2, 100, 14, 12, 6, 5, 1]
print tree.createBySortList('after','mid',after,mid)
''' #双亲节点表示的 节点生成的构造法 #混合节点表示的 节点生成的构造法 
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/sinat_33829806/article/details/78477120
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞