PAT 甲级 1043 Is It a Binary Search Tree

本文介绍了一种通过给定的先序序列来判断其是否构成二叉搜索树(BST)或其镜像的方法,并提供了完整的C++实现及部分Python实现。通过构建树并比较先序遍历结果来验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1043 Is It a Binary Search Tree

题目大意:给出一棵树的先序序列,判断它是否是一个BST或者一个镜面BST

思路:这题主要是树的遍历问题,先假设该树是一棵BST,按照BST的方法建树,然后输出建好树后的先序序列,若是与原数列从小到大排列相同则说明是BST;如果不相同则按照相反的方式遍历这棵树,若得到的先序序列与原数列从大到小排列则说明是镜面BST;否则输出NO。C++完美AC,python测试点5一直非零返回,也不准备找了,花的时间太长了。顺便提一嘴python没有引用真的挺不方便

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

def insert(node,x):
    if node==None:
        node=Node(x)
    elif x<node.data:
        node.left=insert(node.left,x)
    else:
        node.right=insert(node.right,x)
    return node

def postTraversal(root):
    global postList
    if root!=None:
        postTraversal(root.left)
        postTraversal(root.right)
        postList.append(root.data)
    else:
        return

def postMirrorTraversal(root):
    global postMirrorList
    if root!=None:
        postMirrorTraversal(root.right)
        postMirrorTraversal(root.left)
        postMirrorList.append(root.data)
    else:
        return

def preTraversal(root):
    global preList
    if root!=None:
        preList.append(root.data)
        preTraversal(root.left)
        preTraversal(root.right)
    else:
        return

def preMirrorTraversal(root):
    global preMirrorList
    if root!=None:
        preMirrorList.append(root.data)
        preMirrorTraversal(root.right)
        preMirrorTraversal(root.left)
    else:
        return

n=int(input())
pre=list(map(int,input().split()))
root=Node(pre[0])
for i in range(1,len(pre)):
    insert(root,pre[i])
postList=[]
postMirrorList=[]
preList=[]
preMirrorList=[]
preTraversal(root)
preMirrorTraversal(root)
if preList==pre:
    print("YES")
    postTraversal(root)
    for i in range(len(postList)):
        if i!=0:
            print(" ",end="")
        print(postList[i],end="")
elif preMirrorList==pre:
    print("YES")
    postMirrorTraversal(root)
    for i in range(len(postMirrorList)):
        if i!=0:
            print(" ",end="")
        print(postMirrorList[i],end="")
else:
    print("NO",end="")

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值