A Binary Search Tree (BST) is recursively defined as A Binary Tree which has the following properties:
The left subtree of a node contains only nodes with keys is less than The node 's key.
The right subtree of a node contains only nodes with keys greater than or equal to The node 's key.
Both the left and right subtrees must also be binary search trees.
If we swap the left and right subtrees of every node, then the resulting tree is called the Mirror Image of a BST.
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.
Input Specification:
Each input file contains one test case. For Each case, the first line contains a positive integer N (1000) or less. Then N integer keys are given in the next line. All the Numbers in a line are separated by a space.
The Output Specification:
First For each test case, 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, the 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.
The Sample Input 1:
7
On the 8th of June 5 July 10, 11
The Sample Output 1:
YES
5 6 7 8 November 10 8
The Sample Input 2:
7
10 of 11 8 August 6 7 5
The Sample Output 2:
YES
11 August 10 5 6 7 8
The Sample Input 3:
7
On the 8th of June 5 10 9 11
The Sample Output 3:
NO
Code:
#include
using namespace std;
Int preo [1000].
Bool wrong=0;
Struct Node {
The int data;
Node * lchild;
Node * rchild;
};
The Node * create (int preL, int preR)
{
//printf (" preL=% d, preR=% d \ n ", preL, preR);
If (preL & gt; PreR) return NULL;
The root Node *=new Node;
int k;
Bool flag;
Root - & gt; Data=https://bbs.csdn.net/topics/preo [preL];
//printf (" root - & gt; data=https://bbs.csdn.net/topics/%d/n ", root - & gt; The data);
If (preL & lt; PreR)
{
If (preo [preL + 1]
For (int I=preL + 1; i <=preR; I++)
{
If (flag==0)
{
If (preo [I]
else break;
}
If (flag==1)
{
If (preo [I] & gt;=preo [preL])
K=I;
else break;
}
}
For (int I=k + 1; i <=preR; I++)
{
If ((flag==0 & amp; & Preo [I]
Wrong=1;
Return the root;
}
}
}
The else k=preL;
Root - & gt; Lchild=the create (preL + 1, k);
Root - & gt; Rchild=the create (k + 1, preR);
Return the root;
}
Int k=0;
Void postorder (Node * root)
{
If (root==NULL) return;
//printf (" % d \ n ", root - & gt; The data);
//printf (" k=% d \ n ", k);
Postorder (root - & gt; Lchild);
Postorder (root - & gt; Rchild);
If (k!=0) printf (" ");
Printf (" % d ", root - & gt; The data);
k++;
}
Int main (void)
{
Int N;
The root Node *=NULL;
The scanf (" % d ", & amp; N);
for (int i=0; i
The scanf (" % d ", & amp; Preo [I]);
}
Root=the create (0, N - 1);
//printf (" % d \ n ", root - & gt; The data);
If (wrong==1)
Printf (" NO ");
The else
{
Printf (" YES \ n ");
Postorder (root);
}
return 0;
}