一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
- 其左子树中所有结点的键值小于该结点的键值;
- 其右子树中所有结点的键值大于等于该结点的键值;
- 其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
输入格式:
输入的第一行给出正整数 N(≤1000)。随后一行给出 N 个整数键值,其间以空格分隔。
输出格式:
如果输入序列是对一棵二叉搜索树或其镜像进行前序遍历的结果,则首先在一行中输出 YES
,然后在下一行输出该树后序遍历的结果。数字间有 1 个空格,一行的首尾不得有多余空格。若答案是否,则输出 NO
。
输入样例 1:
7
8 6 5 7 10 8 11
输出样例 1:
YES
5 7 6 8 11 10 8
输入样例 2:
7
8 10 11 8 6 7 5
输出样例 2:
YES
11 8 10 7 5 6 8
输入样例 3:
7
8 6 8 5 10 9 11
输出样例 3:
NO
提交结果:
代码:
def judge(start, end):
if start > end:
return
node1 = start + 1
node2 = end
if not flag:
while node1 <= end and a[start] > a[node1]:
node1 += 1
while node2 > start and a[start] <= a[node2]:
node2 -= 1
else:
while node1 <= end and a[start] <= a[node1]:
node1 += 1
while node2 > start and a[start] > a[node2]:
node2 -= 1
if node1 - node2 != 1: # 因为要刚好越过分界线
return
judge(start + 1, node2) # 向左子树递归
judge(node1, end) # 向右子树递归
ans.append(str(a[start])) # 将当前的父节点放入答案
# 如果我们发现是一个二叉搜索树那么ans存的就是后根遍历的结果,
# 因为是递归左右子树后才放入ans中的
n = int(input())
a = list(map(int, input().split()))
flag = False
ans = []
judge(0, n - 1)
if len(ans) != n:
flag = True
ans.clear()
judge(0, n - 1)
if len(ans) == n:
print("YES")
print(" ".join(ans))
else:
print("NO")