1043 Is It a Binary Search Tree (25 分)(算法笔记)

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.

思路:

  1. 先根据给出数据建立二叉搜索树
  2. 假设给出序列是BST的前序,将给出序列与建立的二叉搜索树前序序列比较
  3. 如果相等说明正确,输出后序排列。不等则比较是否为镜像二叉树,相等输出后序排列,不等则说明给出数据不是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 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值