<span style="background-color: rgb(250, 250, 250); font-family: 'Droid Sans', Verdana, 'Microsoft YaHei', Tahoma, sans-serif; line-height: 1em;"><span style="font-size:24px;">04-树4. Search in a Binary Search Tree (25)</span></span>
<span style="background-color: rgb(250, 250, 250); font-family: 'Droid Sans', Verdana, 'Microsoft YaHei', Tahoma, sans-serif; line-height: 1em;"><span style="font-size:24px;">04-树4. Search in a Binary Search Tree (25)</span></span>
To search a key in a binary search tree, we start from the root and move all the way down, choosing branches according to the comparison results of the keys. The searching path corresponds to a sequence of keys. For example, following {1, 4, 2, 3} we can find 3 from a binary search tree with 1 as its root. But {2, 4, 1, 3} is not such a path since 1 is in the right subtree of the root 2, which breaks the rule for a binary search tree. Now given a sequence of keys, you are supposed to tell whether or not it indeed correspnds to a searching path in a binary search tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers N and M (<=100) which are the total number of sequences, and the size of each sequence, respectively. Then N lines follow, each gives a sequence of keys. It is assumed that the keys are numbered from 1 to M.
Output Specification:
For each sequence, print in a line "YES" if the sequence does correspnd to a searching path in a binary search tree, or "NO" if not.
Sample Input:3 4 1 4 2 3 2 4 1 3 3 2 4 1Sample Output:
YES NO NO
思路:题目的意思是判断是否是一个二叉搜索树序列,首先我想到的是,建立一个二维数组存储数据,然后用两个循环判断输入的每一个key。显然这个方法并不好。既然已经学会了二叉树的建立,那就用递归的方法实现实时判断。PAT的测试也并不要求一定要将输入全部完成才能输出。明确了之后只需根据二叉搜索树的特点,在每次插入的时候判断其另一子树是否为空就好。
代码:
#include<iostream> using namespace std; typedef int ElementType; typedef struct TreeNode *BinTree; typedef BinTree Position; typedef struct TreeNode{ ElementType data; BinTree Lchild; BinTree Rchild; }; bool Insert_BST(BinTree *T, int item); int main(int argc, char *argv[]) { int N, M; cin >> N >> M; for (int i = 0; i < N; i++) { bool flag = true; BinTree T = NULL; for (int j = 0; j < M; j++) { int n; cin >> n; if (flag&&!Insert_BST(&T, n)) flag = false; } if (flag) cout << "YES" << endl; else cout << "NO" << endl; } system("pause"); return 0; } bool Insert_BST(BinTree *T, int item) { if (!*T) { *T = (BinTree)malloc(sizeof(struct TreeNode)); (*T)->data = item; (*T)->Lchild = (*T)->Rchild = NULL; } else {//Judge if (item < (*T)->data && (*T)->Rchild == NULL) { if (!Insert_BST(&(*T)->Lchild, item)) return false; } else if (item>(*T)->data && (*T)->Lchild == NULL) { if (!Insert_BST(&(*T)->Rchild, item)) return false; } else return false;//wrong,dose not insert } return true; }