L2-004. 这是二叉搜索树吗?
来源:互联网 发布:果壳网和知乎 编辑:程序博客网 时间:2024/06/04 18:35
给一颗二叉搜索树的前序遍历,问你这是一颗二叉搜索树吗。
在创建的时候,一旦往树的右边创建,就不能往左边走了,否者就GG。
#include <iostream>#include <stdio.h>#include <string.h>#include <malloc.h>using namespace std;struct node{ int x; bool l,r; struct node *left; struct node *right;};int p[1005];int l,r;int flag;struct node *newtree(struct node *t,int a){ struct node *p,*q; p=t; if(l==1){ while(p!=NULL){ if(a>=p->x){ p->l=0; q=p; p=p->right; } else{ if(p->l==1){ q=p; p=p->left; } else{ flag=1; break; } } }} else if(l==0) while(p!=NULL){ if(a>=p->x){ // cout<<p->r<<" "<<p->x<<" "<<a<<endl; if(p->r==1){ q=p; p=p->right; } else{ flag=1; break; } } else{ p->r=0; q=p; //cout<<p->x<<" "<<p->r<<endl; p=p->left; } } p=(struct node *)malloc(sizeof(struct node)); p->x=a; // cout<<p->x<<endl; if(a>=q->x){ q->right=p; } else q->left=p; p->l=1; p->r=1; p->left=NULL; p->right=NULL; return t;}void houxu(node *t){ node *p; p=t; if(p==NULL) return ; houxu(p->left); houxu(p->right); if(flag==0){ cout<<p->x; flag=1; } else{ cout<<" "<<p->x; }}void houxu1(node *t){ node *p; p=t; if(p==NULL) return ; houxu1(p->right); houxu1(p->left); if(flag==0){ cout<<p->x; flag=1; } else{ cout<<" "<<p->x; }}int main(){ int n; while(scanf("%d",&n)!=EOF){ node *tree; flag=0; for(int i=0;i<n;i++){ scanf("%d",&p[i]); } tree=(struct node *)malloc(sizeof(struct node)); tree->x=p[0]; // cout<<tree->x<<endl; if(p[1]<p[0]){ l=1; r=0; }else{ l=0; r=1; } //tree=NULL; tree->left=NULL; tree->right=NULL; tree->l=1; tree->r=1; for(int i=1;i<n;i++){ tree=newtree(tree,p[i]); //cout<<tree->x<<endl; } //cout<<tree->x<<endl; if(flag==0) { printf("YES\n"); //printf("") if(l==1) houxu(tree); else { houxu1(tree); } } else{ printf("NO"); } cout<<endl; } return 0;}
0 0
- L2-004. 这是二叉搜索树吗?
- PAT L2-004. 这是二叉搜索树吗?
- PAT L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- PAT L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗
- PAT--L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗?
- L2-004. 这是二叉搜索树吗? (搜索二叉树的性质)
- CodeMirror源码编辑器
- css中强制换行word-break、word-wrap、white-space区别实例说明
- iOS开发笔记
- 极光推送demo
- windows下zookeeper伪集群搭建
- L2-004. 这是二叉搜索树吗?
- 每天一个 Linux 命令(37):date命令
- 【LeetCode】18. 4Sum
- C# 中GUID生成格式的四种格式
- 26. Remove Duplicates from Sorted Array
- UNIX网络编程卷一 第三章 地址定义及相关函数
- C#递归调用
- Verilog基本模型(Basic Modelling)
- PHP中表单没有问题但是$_FILES为空的解决办法