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





