二叉树 Python的一些操作

例如我想创建如下的二叉树,该怎么办呢?


所幸的是Python中提供了像c语言里面的结构一样的东西,那么这个二叉树的结构就可以用类来实现,首先创建一个类:

class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

鉴于此例中节点较少,可以考虑使用手动输入的方式来构造这颗树,即如下:

ne = Node('e')
nf = Node('f')
ng = Node('g')
nd = Node('d'); nd.right = ne
nb = Node('b'); nb.left = nd; nb.right = nf
nc = Node('c'); nc.right = ng
root = Node('a'); root.left = nb; root.right = nc

树构造好之后,当然就要来到三种遍历方式了:

  1. 前序
  2. 中序
  3. 后序

1. 前序遍历的要点是先根再左后右,而且对每个节点都是如此,这个遍历的方式可以使用递归来实现,如下

def qianxu(root):
    if not root: return
    print(root.val, end=' ')
    qianxu(root.left)
    qianxu(root.right)
qianxu(root)

输出结果为不出所料。

2. 中序

def zhongxu(root):
    if not root: return
    zhongxu(root.left)
    print(root.val, end=' ')
    zhongxu(root.right)
zhongxu(root)

3. 后序

def houxu(root):
    if not root: return
    houxu(root.left)
    houxu(root.right)
    print(root.val, end=' ')
houxu(root)

看到这里,不得不佩服递归的强大。

还有一个好玩的就是怎么找路径的问题,这里可以借鉴前序遍历,比如说找节点 f 的路径,可以怎么玩呢?看看如下的方法:

path = []
def findPath(root, char):
    if not root: return
    path.append(root.val)
    if root.val==char:
        print(' '.join(path))
    findPath(root.left, char)
    findPath(root.right, char)
findPath(root, 'f')

这段代码的输出结果为 a b d e f,差不多就是前序遍历(a b d e f c g)到 f 的部分,其实我们希望见到的结果是 a b f, 那么怎么把多余的d e去掉呢,其实很简单,在函数的最后一行加上个path.pop()就可以了,是不是很神奇。

完整代码如下:

class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

ne = Node('e')
nf = Node('f')
ng = Node('g')
nd = Node('d'); nd.right = ne
nb = Node('b'); nb.left = nd; nb.right = nf
nc = Node('c'); nc.right = ng
root = Node('a'); root.left = nb; root.right = nc

def qianxu(root):
    if not root: return
    print(root.val, end=' ')
    qianxu(root.left)
    qianxu(root.right)
qianxu(root)
print()
def zhongxu(root):
    if not root: return
    zhongxu(root.left)
    print(root.val, end=' ')
    zhongxu(root.right)
zhongxu(root)
print()
def houxu(root):
    if not root: return
    houxu(root.left)
    houxu(root.right)
    print(root.val, end=' ')
houxu(root)
print()
path = []
def findPath(root, char):
    if not root: return
    path.append(root.val)
    if root.val==char:
        print(' '.join(path))
    findPath(root.left, char)
    findPath(root.right, char)
    path.pop()
findPath(root, 'f')

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值