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
原创粉丝点击