关于二叉查找树中的某个节点的前趋和后继的算法(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)]
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/bojdoog/article/details/50850561
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞