#include <bits/stdc++.h>
using
namespace
std;
bool
checkInorderPreorderUtil(
int
inStart,
int
inEnd,
int
& preIndex,
int
preorder[],
unordered_map<
int
,
int
>& inorderIndexMap)
{
if
(inStart > inEnd)
return
true
;
int
rootData = preorder[preIndex];
preIndex++;
if
(inorderIndexMap.find(rootData)
== inorderIndexMap.end())
return
false
;
int
inorderIndex = inorderIndexMap[rootData];
if
(!(inStart <= inorderIndex
&& inorderIndex <= inEnd))
return
false
;
int
leftInorderStart = inStart;
int
leftInorderEnd = inorderIndex - 1;
int
rightInorderStart = inorderIndex + 1;
int
rightInorderEnd = inEnd;
if
(!checkInorderPreorderUtil(
leftInorderStart, leftInorderEnd,
preIndex, preorder, inorderIndexMap))
return
false
;
else
return
checkInorderPreorderUtil(
rightInorderStart, rightInorderEnd,
preIndex, preorder, inorderIndexMap);
}
string checkInorderPreorder(
int
pre[],
int
in[],
int
n)
{
unordered_map<
int
,
int
> inorderIndexMap;
for
(
int
i = 0; i < n; i++)
inorderIndexMap[in[i]] = i;
int
preIndex = 0;
if
(checkInorderPreorderUtil(
0, n - 1, preIndex,
pre, inorderIndexMap)) {
return
"Yes"
;
}
else
{
return
"No"
;
}
}
int
main()
{
int
pre[] = { 1, 2, 4, 5, 7, 3, 6, 8 };
int
in[] = { 4, 2, 5, 7, 1, 6, 8, 3 };
int
N =
sizeof
(pre) /
sizeof
(pre[0]);
cout << checkInorderPreorder(pre, in, N);
return
0;
}