1119. Pre- and Post-order Traversals

来源:互联网 发布:suse linux snmp配置 编辑:程序博客网 时间:2024/05/06 10:23
#include <stdio.h>typedef struct TreeNode {int left;int right;}TreeNode;int pre[30], post[30], in[30], IsUnique=1,flag=0;TreeNode t[30];void BuildTree(int PreBegin, int PreEnd, int PostBegin, int PostEnd);void InOrder(int root);int main(){int n, i;scanf("%d", &n);for (i = 0; i < n; i++)scanf("%d", &pre[i]);for (i = 0; i < n; i++)scanf("%d", &post[i]);BuildTree(0, n - 1, 0, n - 1);//for (i = 0; i < n; i++)//printf("%d %d\n", t[i].left,t[i].right);if (IsUnique)printf("Yes\n");elseprintf("No\n");InOrder(pre[0]);printf("\n");return 0;}void BuildTree(int PreBegin, int PreEnd, int PostBegin, int PostEnd){if (PreBegin == PreEnd) {t[pre[PreBegin]-1].left = -1;t[pre[PreBegin]-1].right = -1;return;}int root = pre[PreBegin], ChildRoot = pre[PreBegin+1],i, LeftSize = 0,RightSize=0;/*ChildRoot可能是左子树的根也有可能是右子树的根*/for (i = PostBegin; i < PostEnd; i++)if (post[i] == ChildRoot)break;/*若是右子树的根,则i==postend-1;若i==postend-1,可能无左子树或右子树*/if (i == PostEnd - 1)/*若不等则去掉为左子树的可能性*/IsUnique = 0;/*当成是左子树的根来做*/LeftSize = i - PostBegin + 1;RightSize = PostEnd - i - 1;if (LeftSize > 0) {t[root - 1].left = ChildRoot;BuildTree(PreBegin + 1, PreBegin + LeftSize , PostBegin, i);}elset[root - 1].left = -1;if (RightSize > 0) {t[root - 1].right = post[PostEnd - 1];BuildTree(PreBegin + LeftSize + 1, PreEnd, i + 1, PostEnd - 1);}elset[root - 1].right = -1;}void InOrder(int root){if (t[root - 1].left != -1)InOrder(t[root - 1].left);if (flag)printf(" %d", root);else {printf("%d", root);flag = 1;}if (t[root - 1].right != -1)InOrder(t[root - 1].right);return;}

0 0