关于二叉查找树中的某个节点的前趋和后继的算法(Python实现)

废话不多说,代码如下:
# -*- coding:utf-8 -*-
def Tree_Predecessor(x):
    '''给定一个二叉查找树的节点z,要求找出在中序遍历下它的前趋'''
    if left[x] != None:
        return Tree_Maximum(left[x])
    y = p[x]
    while y != None and x == left[y]:
        x = y
        y = p[y]
    return y

def Tree_Maximum(x):
    '''找出以x节点为根的树中的最大关键字元素'''
    if right[x] != None:
        return Tree_Maximum(right[x])
    return x

def Tree_Successor(x):
    '''给定一个二叉树中的节点z,要求找出在中序遍历顺序下它的后继'''
    if right[x] != None:
        return Tree_Minimum(right[x])
    y = p[x]
    while y != None and x == right[y]:
        x = y
        y = p[y]
    return y

def Tree_Minimum(x):
    '''找出以x节点为根的树中的最小关键字元素'''
    while left[x] != None:
        return Tree_Minimum(left[x])
    return x

if __name__ == '__main__':
    key = [15,6,18,3,7,17,2,4,9,13,20]
    left = [1,3,5,6,None,None,None,None,None,8,None]
    right = [2,4,10,7,9,None,None,None,None,None,None]
    p = [None,0,0,1,1,2,3,3,9,4,2]
    print key[Tree_Predecessor(9)]         #输出key[9]=13的前趋和后继
    print key[Tree_Successor(9)]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值