L2-004 这是二叉搜索树吗?
Posted alingmaomao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了L2-004 这是二叉搜索树吗?相关的知识,希望对你有一定的参考价值。
这个题要注意的是:右节点时大于等于根节点的。
#include<iostream> #include<vector> using namespace std; const int maxn = 1e3 + 10; int pre[maxn], n; bool is; vector<int>ss; void f(int l, int r){ if (l > r)return; int tr = l + 1; int tl = r; if (!is){ while (tr <= r&&pre[tr] < pre[l])tr++; while (tl > l&&pre[tl]>=pre[l])--tl; } else{ while (tr <= r&&pre[tr] >= pre[l])tr++; while (tl > l&&pre[tl] < pre[l])--tl; } if (tr - tl != 1)return; f(l + 1, tl); f(tr, r); ss.push_back(pre[l]); } int main(){ cin >> n; for (int i = 0; i < n; ++i)cin >> pre[i]; f(0, n - 1); if (ss.size() != n){ is = 1; ss.clear(); f(0, n - 1); } if (ss.size() != n)cout << "NO" << endl; else{ cout << "YES" << endl; cout << ss[0]; for (int i = 1; i < n; ++i) cout << " " << ss[i]; cout << endl; } }
以上是关于L2-004 这是二叉搜索树吗?的主要内容,如果未能解决你的问题,请参考以下文章
PTA L2-004 这是二叉搜索树吗?-判断是否是对一棵二叉搜索树或其镜像进行前序遍历的结果 团体程序设计天梯赛-练习集