二叉树的实现

二叉树的节点表示以及树的创建

通过使用Node类中定义三个属性,分别为elem本身的值,还有lchth左孩子和rchth右孩子
然后我们就可以先写个节点类

class Node(object):
    def __init__(self,item):
    	#数据
        self.item=item
        #左叶子节点
        self.lcth=None
        #右叶总节点
        self.rcth=None

定义好节点类后我们就可以写树类了

class Tree(object):
    def __init__(self):
    	#根节点
        self.root=None

我们这下就要实现树的基本功能了,添加元素add()与遍历trav() 我们先看看添加元素的代码

def add(self,item):
    node=Node(item)
    if self.root is None:
    	#当第一次添加元素根节点是None的时候
        self.root=node
        return
    #模拟一个队列
    queue=[self.root]
    while queue:
        cur_ode=queue.pop(0)
        if cur_ode.lcth is None:
            cur_ode.lcth=node
            return
        else:
            queue.append(cur_ode.lcth)
        if cur_ode.rcht is None:
            cur_ode.rcht=node
            return
        else:
            queue.append(cur_ode.rcht)

广度遍历树 trav():

def trav(self):
    if self.root is None:
        return
    queue=[self.root]
    while queue:
        cur_ode=queue.pop(0)
        print(cur_ode.item,end=" ")
        if cur_ode.lcth is not None:
            queue.append(cur_ode.lcth)
        if cur_ode.rcth is not None:
            queue.append(cur_ode.rcth)

先序遍历树(递归思想)

def preoeder(self,root):
    if root is None:
        return
    print(root.item,end=" ")
    self.preoeder(root.lcth)
    self.preoeder(root.rcth)

中序遍历(递归思想)

def inorder(self,root):
    if root is None:
        return
    self.inorder(root.lcth)
    print(root.item,end=" ")

后序遍历(递归思想):

def postorder(self,root):
    if root is None:
        return
    self.postorder(root.lcth)
    self.postorder(root.rcth)
    print(root.item,end=" ")

调用实现

if __name__ =="__main__":
    t=Tree()
    t.add(5)
    t.add(6)
    t.trav()
    print()
    t.preoeder(t.root)
    print()
    t.inorder(t.root)
    t.postorder(t.root)
上面的遍历是根据树的广度优先遍历来做的,说到广度优先遍历我给放大家再讲几点

广度优先遍历(层次遍历)

从树的root开始,从上到下从从左到右遍历整个树的节点,根据树的层次从根节点层从左到右开始数

先序遍历

在先序遍历中,我们先访问根节点,然后递归使用先序遍历访问左子树,再递归使用先序遍历访问右子树
根节点->左子树->右子树

中序遍历

在中序遍历中,我们递归使用中序遍历访问左子树,然后访问根节点,最后再递归使用中序遍历访问右子树
左子树->根节点->右子树

后序遍历

在后序遍历中,我们先递归使用后序遍历访问左子树和右子树,最后访问根节点
左子树->右子树->根节点
在这里插入图片描述
广度遍历:0,1,2,3,4,5,6,7,8,9
先序遍历:0,1,3,7,8,4,9,2,5,6
中序遍历:7,3,8,1,9,4,0,5,2,6
后序遍历:7,8,3,9,4,1,5,6,2,0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值