分享:二叉树的插入数据与查找数据的方法

# -*- coding: UTF-8 -*-

#Insert
def insertBintree(tree,num):
    if tree == []:
        tree.extend([num,[],[]])
    elif num <= tree[0]:
        insertBintree(tree[1],num)
    elif num > tree[0]:
        insertBintree(tree[2],num)
    return tree

mytree = [56,
    [32,[27,[],[]],[46,[],[]]],
    [77,
        [74,[60,[],[]],[]],
        [108,[],[]]]]
print(insertBintree(mytree,70))

 

 

# -*- coding: UTF-8 -*-

#Search
def searchBintree(tree,num):
    if tree == []:
        return False
    if num == tree[0]:
        return True
    if num < tree[0]:
        return searchBintree(tree[1],num)
    if num > tree[0]:
        return searchBintree(tree[2],num)

mytree = [56,
    [32,[27,[],[]],[]],
    [77,
        [74,[60,[],[]],[]],
        []]]
if searchBintree(mytree,60):
    print(‘Yes’)
else:
    print(‘No’)

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/hpwzjz/article/details/81457761
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞