Is It a Binary Search Tree (25)

来源:互联网 发布:湘阴农村淘宝 编辑:程序博客网 时间:2024/06/05 04:25

题目分析:

1、要求根据给出的数字建立二叉树

2、看看给出的数字序列是不是先序遍历,是则给出后序遍历

3、看看给出的数字序列是不是镜像的先序遍历,是则给出镜像的后序遍历


注意地方:

手写解题的时候,要注意镜像是左边大于等于根节点,右边小于根节点,完全镜像。


遍历方法:

1、先序:根节点,左儿子调用递归,右儿子调用递归

2、中序、后序类似

void PreOrder(Tree *root){if (root != NULL){result1[count1++] = root->key;PreOrder(root->left);PreOrder(root->right);}}

解题代码:

#include "iostream"#include "vector"#include "string"#include "cstring"using namespace std;struct Tree{int key;Tree *left;Tree *right;Tree() {key = -1;left = NULL;right = NULL;}};int result1[1000], result2[1000];int result3[1000], result4[1000];int count1 = 0, count2 = 0;int count3 = 0, count4 = 0;void PreOrder(Tree *root){if (root != NULL){result1[count1++] = root->key;PreOrder(root->left);PreOrder(root->right);}}void MirrorPreOrder(Tree *root){if (root != NULL){result2[count2++] = root->key;MirrorPreOrder(root->right);MirrorPreOrder(root->left);}}void PostOrder(Tree *root){if (root != NULL){PostOrder(root->left);PostOrder(root->right);result3[count3++] = root->key;}}void MirrorPostOrder(Tree *root){if (root != NULL){MirrorPostOrder(root->right);MirrorPostOrder(root->left);result4[count4++] = root->key;}}int main(){int N;int data[1000];cin >> N;for (int i = 0; i < N; i++)cin >> data[i];Tree *root = (Tree*)malloc(sizeof(Tree));root->key = data[0];root->left = NULL;root->right = NULL;Tree *operat = root;for (int i = 1; i < N; i++){Tree *temp = root;while (1){if (temp->key > data[i]){if (temp->left == NULL){temp->left = (Tree*)malloc(sizeof(Tree));temp = temp->left;temp->key = data[i];temp->left = NULL;temp->right = NULL;break;}elsetemp = temp->left;}else{if (temp->right == NULL){temp->right = (Tree*)malloc(sizeof(Tree));temp = temp->right;temp->key = data[i];temp->left = NULL;temp->right = NULL;break;}elsetemp = temp->right;}}}bool mirror = true;bool pre = true;PreOrder(root);MirrorPreOrder(root);for (int i = 0; i < N; i++){if (result1[i] != data[i]){pre = false;}if (result2[i] != data[i]){mirror = false;}}if (pre == false && mirror == false){cout << "NO";}else if (pre == true){cout << "YES" << endl;PostOrder(root);for (int i = 0; i < N - 1; i++)cout << result3[i] << ' ';cout << result3[N - 1];}else{cout << "YES"<<endl;MirrorPostOrder(root);for (int i = 0; i < N - 1; i++)cout << result4[i] << ' ';cout << result4[N - 1];}}


0 0
原创粉丝点击