1043. Is It a Binary Search Tree
来源:互联网 发布:js中遍历dom元素 编辑:程序博客网 时间:2024/05/22 00:22
这道题……没想到镜像BST和BST先序怎么转换,直接复制了一下函数。
#include <stdio.h>#include <stdlib.h>int IsBST(int Pre[],int begin,int end,int Post[],int PosBegin,int PosEnd);int IsMBST(int Pre[], int begin, int end, int Post[], int PosBegin, int PosEnd);int main(){int n,i,Is;scanf("%d", &n);int *Pre = (int*)malloc(sizeof(int)*n);int *Post = (int*)malloc(sizeof(int)*n);for (i = 0; i < n; i++)scanf("%d", &Pre[i]);Is = IsBST(Pre, 0, n - 1, Post,0,n-1);if (Is) {printf("YES\n");for (i = 0; i < n - 1; i++)printf("%d ", Post[i]);printf("%d", Post[n-1]);}else if (Is = IsMBST(Pre, 0, n - 1, Post, 0, n - 1)) {printf("YES\n");for (i = 0; i < n - 1; i++)printf("%d ", Post[i]);printf("%d", Post[n - 1]);}else printf("NO"); free(Pre);free(Post);return 0;}int IsBST(int Pre[], int begin, int end, int Post[],int PosBegin,int PosEnd){int i,Root = Pre[begin],Pos,LeftSize,RightSize;if (begin > end)/*树空*/return 1;for (i = begin + 1; i <= end; i++) {if (Pre[i] >= Root)break;}Pos = i;while (i <= end)if (Pre[i] < Root)return 0;else i++;Post[ PosEnd ] = Root;LeftSize = Pos - begin - 1;RightSize = end - Pos + 1;return IsBST(Pre, begin + 1, Pos - 1, Post,PosBegin,PosBegin+LeftSize-1) && IsBST(Pre, Pos, end, Post,PosEnd-RightSize,PosEnd-1);}int IsMBST(int Pre[], int begin, int end, int Post[], int PosBegin, int PosEnd){int i, Root = Pre[begin], Pos, LeftSize, RightSize;if (begin > end)/*树空*/return 1;for (i = begin + 1; i <= end; i++) {if (Pre[i] < Root)break;}Pos = i;while (i <= end)if (Pre[i] >= Root)return 0;else i++;Post[PosEnd] = Root;LeftSize = Pos - begin - 1;RightSize = end - Pos + 1;return IsMBST(Pre, begin + 1, Pos - 1, Post, PosBegin, PosBegin + LeftSize - 1) && IsMBST(Pre, Pos, end, Post, PosEnd - RightSize, PosEnd - 1);}
0 0
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043.Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree
- PAT A 1043. Is It a Binary Search Tree (25)
- PAT-A-1043. Is It a Binary Search Tree (25)
- pat-a 1043. Is It a Binary Search Tree (25)
- Is It a Binary Search Tree (25)
- PAT_1043. Is It a Binary Search Tree
- 1043. Is It a Binary Search Tree (25)
- DES算法资料
- Linux(CentOS)安装完成后连接网络
- Android adb命令的使用
- [2]Core Dump调试应用程序
- KiCad设计PCB-37-按键及其他几个引脚的布线
- 1043. Is It a Binary Search Tree
- 汇编语言学习笔记(可持续补充)
- swift type casting
- 队列的基本操作
- bzoj1604:奶牛的邻居(treap)
- [AHK]进制转换
- Linux--常用脚本
- 【Struts2学习】 (2) Struts2开发HelloWorld实例
- Xilinx FPGA中SRL(移位寄存器)资源