class Node{
constructor(val){
this
.data = val;
this
.left =
null
;
this
.right =
null
;
}
}
let preIndex = 0;
let notPossible =
false
;
function
buildTreeFromInorderPreorder(inStart, inEnd,
preorder, inorderIndexMap){
if
(inStart > inEnd){
return
null
;
}
let rootData = preorder[preIndex];
let root =
new
Node(rootData);
preIndex++;
if
(inorderIndexMap.has(rootData) ==
false
){
notPossible =
true
;
return
root;
}
let inorderIndex = inorderIndexMap.get(rootData);
if
(!(inStart <= inorderIndex && inorderIndex <= inEnd)){
notPosstible =
true
;
return
root;
}
let leftInorderStart = inStart;
let leftInorderEnd = inorderIndex - 1;
let rightInorderStart = inorderIndex + 1;
let rightInorderEnd = inEnd;
root.left = buildTreeFromInorderPreorder(
leftInorderStart, leftInorderEnd, preorder, inorderIndexMap);
if
(notPossible ==
true
)
return
root;
root.right = buildTreeFromInorderPreorder(
leftInorderStart, leftInorderEnd, preorder, inorderIndexMap);
return
root;
}
let postIndex = 0;
function
checkPostorderCorrect(root, postOrder){
if
(root ==
null
)
return
true
;
if
(!checkPostorderCorrect(root.left, postOrder))
return
false
;
if
(!checkPostorderCorrect(root.right, postOrder))
return
false
;
return
(root.data == postOrder[postIndex++]);
}
function
printPostorder(root){
if
(root ==
null
)
return
;
printPostorder(root.left);
printPostorder(root.right);
document.write(root.data +
" "
);
}
function
printInorder(root){
if
(root ==
null
)
return
;
printInorder(root.left);
document.write(root.data +
" "
);
printInorder(root.right);
}
function
checktree(preorder, inorder, postorder, N){
if
(N == 0)
return
true
;
inorderIndexMap =
new
Map();
for
(let i = 0; i<N; i++){
inorderIndexMap.set(inorder[i], i);
}
let root = buildTreeFromInorderPreorder(0, N-1,
preorder, inorderIndexMap);
if
(notPossible ==
true
)
return
false
;
return
checkPostorderCorrect(root, postorder);
}
let inOrder = [4, 2, 5, 1, 3];
let preOrder = [1, 2, 4, 5, 3];
let postOrder = [4, 5, 2, 3, 1];
let len = inOrder.length;
if
(checktree(preOrder, inOrder, postOrder, len))
document.write(
"Yes"
);
else
document.write(
"No"
);