【python】给定一棵满二叉树,判定该树是否为二叉搜索树

题目链接:https://www.nowcoder.com/practice/76fb9757332c467d933418f4adf5c73d

题中给出的序列是【从根节点开始,从上到下、同层从左到右的节点序列】

思路:

1. 根据给出的序列,构造树;

2. 根据树,得到中序遍历序列;

3. 根据【二叉搜索树中序递增】的性质,判断该树是否为二叉搜索树。

注意:

读入的数据是字符串,在【步骤2】中序遍历的时候需要把节点类型转换成【int】

class tree:
    def __init__(self,x):
        self.val = x
        self.left = None
        self.right = None
        
def build_tree(array,i):
    if i >= len(array) or array[i] == 'None':
        return None
    root = tree(array[i])
    root.left = build_tree(array,2*i+1)
    root.right = build_tree(array,2*i+2)
    return root

def tin(res,root):
    if not root:
        return 
    tin(res,root.left)
    res.append(int(root.val))
    tin(res,root.right)
    return res

def compare(array):
    if not array:
        return None
    if len(array) == 1:
        return True
    pre = array[0]
    for i in range(1,len(array)):
        if array[i] <= pre:
            return False
        else:
            pre = array[i]
    return True

array = input().split(',')
if not array:
    print(False)
elif len(array) == 1:
    print(True)
else:
    root = build_tree(array,0)
    res = []
    tin_tree = tin(res,root)
    print(compare(tin_tree))

########################## 类似的题目 ###################################

https://www.nowcoder.com/practice/e12c53c925754a07b5f5a2a4dd8fa829

区别仅在于:给的数据格式不同,所以构造树的过程有些不一样。

Python版本的case:73.33%,AC不了,不知道为啥?

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

def build_tree(num,rloc):
    if rloc < 0:
        return None
    a,b,c = num[rloc]
    root = Tree(a)
    root.left = build_tree(num,b-1)
    root.right = build_tree(num,c-1)
    return root

def tin(res,root):
    if not root:
        return
    tin(res,root.left)
    res.append(root.val)
    tin(res,root.right)
    return res

def compare(array):
    if not array:
        return True
    if len(array) == 1:
        return True
    pre = array[0]
    for i in range(1,len(array)):
        if array[i] <= pre:
            return False
        else:
            pre = array[i]
    return True

lst = list(map(int,input().split()))
n = lst[0]
root = lst[1]-1
num = []
for i in range(n):
    lst = list(map(int,input().split()))
    num.append(lst)

if not num:
    print('false')
elif len(num) == 1:
    print('true')
else:
    node = build_tree(num,root)
    res = []
    tin_tree = tin(res,node)
    if compare(tin_tree):
        print('true')
    else:
        print('false')

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值