Files
PAT/html/a1043.html
T

44 lines
1.8 KiB
HTML

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h1>1043. Is It a Binary Search Tree (25)</h1>
<div id="problemContent">
<p>A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:</p>
<ul>
<li>The left subtree of a node contains only nodes with keys less than the node's key.
<li>The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
<li>Both the left and right subtrees must also be binary search trees. </li></li></li></ul>
<p>If we swap the left and right subtrees of every node, then the resulting tree is called the Mirror Image of a BST.</p>
<p>Now given a sequence of integer keys, you are supposed to tell if it is the preorder traversal sequence of a BST or the mirror image of a BST.</p>
<p><b>
Input Specification:
</b></p>
<p>Each input file contains one test case. For each case, the first line contains a positive integer N (&lt;=1000). Then N integer keys are given in the next line. All the numbers in a line are separated by a space.</p>
<p><b>
Output Specification:
</b></p>
<p>For each test case, first print in a line "YES" if the sequence is the preorder traversal sequence of a BST or the mirror image of a BST, or "NO" if not. Then if the answer is "YES", print in the next line the postorder traversal sequence of that tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
</p>
<b>Sample Input 1:</b><pre>
7
8 6 5 7 10 8 11
</pre>
<b>Sample Output 1:</b><pre>
YES
5 7 6 8 11 10 8
</pre>
<b>Sample Input 2:</b><pre>
7
8 10 11 8 6 7 5
</pre>
<b>Sample Output 2:</b><pre>
YES
11 8 10 7 5 6 8
</pre>
<b>Sample Input 3:</b><pre>
7
8 6 8 5 10 9 11
</pre>
<b>Sample Output 3:</b><pre>
NO
</pre>
</div>