1043 Is It a Binary Search Tree (25 分)
…
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N integer keys are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, first print in a line YES if the sequence is the preorder traversal sequence of a BST or the mirror image of a BST, or NO if not. Then if the answer is YES, print in the next line the postorder traversal sequence of that tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
思路:
- 先根据给出数据建立二叉搜索树
- 假设给出序列是BST的前序,将给出序列与建立的二叉搜索树前序序列比较
- 如果相等说明正确,输出后序排列。不等则比较是否为镜像二叉树,相等输出后序排列,不等则说明给出数据不是BST,输出NO。
#include <stdio.h>
#include <vector>
using namespace std;
struct node
{
int data; /* 数据域 */
node* lchild, *rchild; /* 指针域 */
};
void insert(node* &root, int data) {
if (root == NULL) {
/*当到达空节点时,即为需要插入的位置*/
root = new node;
root->data = data;
root->lchild = root->rchild = NULL;
}
else if (root->data > data) insert(root->lchild, data);
else