二叉树的类引用

在python中二叉树的构建是利用类来实现的,在此之前我们先去了解一下什么是类

贴上一篇文章的网址:http://python.jobbole.com/81921/

主要是对这篇文章的总结和整理。

用一个小例子来看一下:

class Test:
    def prt(self):
        print(self)
        print(self.__class__)

t=Test()#类的实例化
t.prt()

执行结果:

<__main__.Test object at 0x000001A4C4FE81D0>
<class '__main__.Test'>

在Python的解释器内部,当我们调用t.prt()时,实际上Python解释成Test.prt(t),也就是说把self替换成类的实例。

让我们看看不加self是什么情况

class Test:
    def prt():
        print(self)
 
t = Test()
t.prt()

结果:

----> 6 t.prt()
TypeError: prt() takes 0 positional arguments but 1 was given

简单来说,使用self,类似与先占用一个位置,之后如果类中有产生了一个实例,就可以将这个参数位置让给实例(自己的理解,不知道对不对)

lst=[1,2,3]
list.reverse(lst)
print(lst)
lst.reverse()
print(lst)

结果:

[3, 2, 1]
[1, 2, 3]
class.function(lst)等价于lst.function()

确实两种调用方法是一样的

 牛客网习题总结:

1. 递归二叉树的序列打印

# -*- coding:utf-8 -*-

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class TreeToSequence:
    def convert(self, root):
        # write code here
        shuchu=[[],[],[]]
        self.xianxu(root,shuchu[0])
        self.zhongxu(root,shuchu[1])
        self.houxu(root,shuchu[2])
        return shuchu
       

    def xianxu(self,root,shuchu):
        if root == None:
            return 0
        else:
            shuchu.append(root.val)
            self.xianxu(root.left,shuchu)
            self.xianxu(root.right,shuchu)
            return shuchu
    def zhongxu(self,root,shuchu):
        if root == None:
            return 0
        else:
            self.zhongxu(root.left,shuchu)
            shuchu.append(root.val)
            self.zhongxu(root.right,shuchu)
            return shuchu
    def houxu(self,root,shuchu):
        if root == None:
            return 0
        else:
            self.houxu(root.left,shuchu)
            self.houxu(root.right,shuchu)
            shuchu.append(root.val)
            return shuchu

2.  非递归二叉树的序列打印

# -*- coding:utf-8 -*-

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class TreeToSequence:
    def convert(self, root):
        # write code here
        shuchu=[[],[],[]]
        self.xianxu(root,shuchu[0])
        self.zhongxu(root,shuchu[1])
        self.houxu(root,shuchu[2])
        return shuchu
    
    def xianxu(self,root,res):
        stack=[]
        stack.append(root)
        while len(stack):
            cur=stack.pop()
            res.append(cur.val)
            if cur.right:
                stack.append(cur.right)
            if cur.left:
                stack.append(cur.left)
        return res
        
        
        
        
    def zhongxu(self,root,res):
        stack=[]
        cur=root
        while cur or len(stack):
            if cur:
                stack.append(cur)
                cur=cur.left
            else:
                node=stack.pop()
                res.append(node.val)
                cur=node.right
        return res
        

    def houxu(self,root,res):
        stack1=[]
        stack2=[]
        stack1.append(root)
        while len(stack1):
            cur = stack1.pop()
            stack2.append(cur.val)
            if cur.left:
                stack1.append(cur.left)
            if cur.right:
                stack1.append(cur.right)
        while len(stack2):
            res.append(stack2.pop())
        return res

3. 如何建立一棵二叉树&统计树中结点个数&树中所有元素之和

树结构:

class Tree:
def __init__(self,x,left=None,right=None):
  self.key=x
  self.left=left
  self.right=right

#构建二叉树
t=Tree(2,Tree(5,Tree(8),Tree(9)),Tree(7,Tree(10),Tree(11)))

#统计数中结点个数

def count_BinTNodes(t):
  if t is None:
    return 0
  else:
    return 1+count_BinTNodes(t.left)+count_BinTNodes(t.right)
coun=count_BinTNodes(t)
print(coun)

#树中所有元素之和
def sum_BinTNodes(t):
  if t is None:
    return 0
  else:
    return t.key+sum_BinTNodes(t.left)+sum_BinTNodes(t.right)


summ=sum_BinTNodes(t)
print(summ)

 

结果:

7
52

 

4.先序遍历&先序遍历每一个元素,并且将None位置输出为#,这样才能准确的理解树的结构&加括号

#先序遍历整棵树
def preorder(t):
    if t is None:
        return
    else:
        print(str(t.key),end="")
        preorder(t.left)
        preorder(t.right)
#先序遍历整棵树,将None位置输出为#,这样才能准确的理解树的结构
preorder(t)
print()

def preorder2(t):
    if t is None:
        print('#',end="")
        return
    else:
        print(str(t.key),end="")
        preorder2(t.left)
        preorder2(t.right)
preorder2(t)
print()

#先序遍历整棵树,将None位置输出为#,这样才能准确的理解树的结构,并输出为(2(5(8##)(9##))(7(10##)(11##)))
def preorder3(t):
    if t is None:
        print('#',end="")
        return
    else:
        print("("+str(t.key),end="")
        preorder3(t.left)
        preorder3(t.right)
        print(")",end="")
preorder3(t)

输出结果:

258971011
258##9##710##11##
(2(5(8##)(9##))(7(10##)(11##)))

 5. 序列化和反序列化(先序)

#二叉树的类引用
class Tree:
    def __init__(self,x,left=None,right=None):
        self.key=x
        self.left=left
        self.right=right
    
#构建二叉树
root=Tree(2,Tree(5,Tree(8),Tree(9)),Tree(7,Tree(10),Tree(11))) 
class Solution:  
    def Serialize(self, root):  
        #"把对象转换为字节序列的过程称为对象的序列化"  
        # write code here  
        def Pre_Order(root):  #先序遍历
            if root:  
                result.append(str(root.key))  #将数字转换为字符
                Pre_Order(root.left)  
                Pre_Order(root.right)  
            else:  
                result.append("#")  
        result = []  
        Pre_Order(root)  
        print(result)
        return ",".join(result)  

#=======================================================================================
    def Deserialize(self, s):  
        #"把字节序列恢复为对象的过程称为对象的反序列化"  
        # write code here  
        s = s.split(",")  
  
        def Change(num):  
            num += 1  
            if num < len(s):  
                if s[num] == "#":  
                    return None  
                root = Tree(int(s[num]))  
                root.left = Change(num)  
                root.right = Change(num)  
                return root  
            else:  
                return None  
  
        num= -1  
        return Change(num)  
t=Solution()
s=t.Serialize(root)
print(s)
#==========================================
m=Solution()
n=m.Deserialize(s)#利用先序序列重新构建了树
print(n)

输出结果:

['2', '5', '8', '#', '#', '9', '#', '#', '7', '10', '#', '#', '11', '#', '#']
2,5,8,#,#,9,#,#,7,10,#,#,11,#,#
<__main__.Tree object at 0x000001A4C5081748>

 

posted @ 2017-10-11 18:32  qxl1993  阅读(336)  评论(0编辑  收藏  举报