博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT--1043 Is It a Binary Search Tree(二叉排序树的建立与判定)
阅读量:195 次
发布时间:2019-02-28

本文共 2309 字,大约阅读时间需要 7 分钟。

思路:

如何判断一个输入序列是否是一颗二叉排序树的前序序列或者是其镜像树的前序序列?
方法一:根据输入序列建立一颗二叉排序树和一颗镜像树,分别再进行前序遍历,若这两棵树中,有一个前序序列和输入序列相同,则输出yes。否则输出no。vector可以用==判断是否相等,故数据的存放用vector来存储。
参考博客:
方法二:还有一个规律是镜像树的后序遍历与其二叉排序树的前序遍历的逆序相同,镜像树的前序遍历与其二叉排序树的后序遍历的逆序相同。对于一颗二叉树来说,其后序遍历是左右根,故其镜像树的前序遍历序列为其后序遍历的逆序也就是根右左。因此可以按照二叉排序树的规则只建立一棵树,之后用根右左的遍历规则得到其镜像树的前序遍历序列。网上也有人用这种方法做。
我用方法一来做。

#include 
#include
#include
#include
using namespace std;struct Node{
Node *lchild, *rchild; int num;};vector
inpVec, preVec, mipreVec, postVec;Node* create(int v){
Node *root = new Node(); root->lchild = root->rchild = NULL; root->num = v; return root;}//建立一颗二叉排序树Node* insert1(Node *root, int v){
if (root == NULL) return create(v); else {
if (v < root->num) root->lchild = insert1(root->lchild, v); else root->rchild = insert1(root->rchild, v); } return root;}//建立一颗镜像树Node* insert2(Node *root, int v){
if (root == NULL) return create(v); else {
if (v >= root->num) root->lchild = insert2(root->lchild, v); else root->rchild = insert2(root->rchild, v); } return root;}//前序遍历void preOrder(Node* root, vector
&vec){ vec.push_back(root->num); if (root->lchild) preOrder(root->lchild, vec); if (root->rchild) preOrder(root->rchild, vec);}//后序遍历void postOrder(Node* root, vector
&vec){ if (root->lchild) postOrder(root->lchild, vec); if (root->rchild) postOrder(root->rchild, vec); vec.push_back(root->num);}int main(){ int n, k; scanf("%d", &n); Node *root1 = NULL, *root2 = NULL; for (int i = 0; i < n; ++i) { scanf("%d", &k); inpVec.push_back(k); //保存输入序列 root1 = insert1(root1, k); root2 = insert2(root2, k); } //分别保存二叉树和镜像树的前序遍历序列 preOrder(root1, preVec); preOrder(root2, mipreVec); if(inpVec == preVec) { printf("YES\n"); postOrder(root1, postVec); for(int i = 0; i < postVec.size(); ++i) { if(i == postVec.size()-1) printf("%d\n", postVec[i]); else printf("%d ", postVec[i]); } } else if(inpVec == mipreVec) { printf("YES\n"); postOrder(root2, postVec); for(int i = 0; i < postVec.size(); ++i) { if(i == postVec.size()-1) printf("%d\n", postVec[i]); else printf("%d ", postVec[i]); } } else printf("NO\n"); return 0;}

转载地址:http://inrn.baihongyu.com/

你可能感兴趣的文章