PAT (Advanced) 1086. Tree Traversals Again (25)
1929 단어 PAT
문제 해결 방법:
실제로 입고 순서는 앞의 순서, 출고 순서는 중간 순서이다. 그러면 두 개의 순서가 있으면 두 갈래 나무를 직접 구성할 수 있고 후속의 순서도 바로 얻을 수 있다.
코드는 다음과 같습니다.
#include
#include
#include
#include
using namespace std;
const int maxn = 30 + 5;
struct Node
{
int id;
Node* lchild, *rchild, *parent;
Node(){id = 0; lchild = NULL; rchild = NULL; parent = NULL;}
};
int preOrder[maxn], inOrder[maxn];
void build(Node* &root, int l1, int r1, int l2, int r2)
{
if(l1 > r1) return ;
root = new Node();
root->id = preOrder[l1];
int k;
for(k = l2; k <= r2; k++)
if(inOrder[k] == preOrder[l1]) break;
int c = k - l2;
build(root->lchild, l1+1, l1+c, l2, k-1);
build(root->rchild, l1+c+1, r1, k+1, r2);
}
void postOrder(Node* root, int &first)
{
if(root->lchild != NULL)
postOrder(root->lchild, first);
if(root->rchild != NULL)
postOrder(root->rchild, first);
if(first) {printf("%d", root->id); first = 0;}
else printf(" %d", root->id);
}
int main()
{
int n;
while(scanf("%d", &n) == 1)
{
stack sta;
int cnt = 0, cPre = 0, cIn = 0;
while(cnt < n)
{
char cmd[5];
int x;
scanf("%s", cmd);
if(cmd[1] == 'u')
{
scanf("%d", &x);
sta.push(x);
preOrder[cPre++] = x;
}
else
{
inOrder[cIn++] = sta.top();
sta.pop();
cnt++;
}
}
Node* root = NULL;
build(root, 0, n-1, 0, n-1);
int first = 1;
postOrder(root, first);
printf("
");
}
return 0;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
PAT A급 1064 Complete Binary Search Tree(30점) 완전 두 갈래 나무, BST1064 Complete Binary Search Tree(30분) A Binary Search Tree (BST) is recursively defined as a binary tree which has the f...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.