我是先复原了二叉树,再对其进行遍历。
这里有个技巧,%*c可以读取换行符,然后存储到一个结构数组里,方便后面构造二叉树,这里读取的时候要左右颠倒,因为题目就是要翻转二叉树,干脆读取的时候就翻转了。
后面就很基础了。
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <cstring>
#include <stack>
#include <queue>
using namespace std;
typedef struct node{
int data;
struct node *left;
struct node *right;
}Node,*b_tree;
int n;
int space = 0;
struct shu{
int left;
int right;
}s[12];
int hash_table[10];
int change(char c){
return c-'0';
}
void complete(b_tree root,int parent){
if(s[parent].left != -1){
b_tree node = new Node;
node->left = node->right = NULL;
node->data = s[parent].left;
root->left = node;
int father = s[parent].left;
complete(root->left, father);
}else{
root->left = NULL;
}
if (s[parent].right != -1) {
b_tree node = new Node;
node->left = node->right = NULL;
node->data = s[parent].right;
root->right = node;
int father = s[parent].right;
complete(root->right, father);
}else{
root->right = NULL;
}
}
void layout (b_tree root){
queue<b_tree> q;
q.push(root);
while (!q.empty()) {
b_tree head = q.front();
q.pop();
printf("%d",head->data);
space++;
if(space < n)
printf(" ");
if(head->left)
q.push(head->left);
if(head->right)
q.push(head->right);
}
}
void inorder(b_tree root){
if (!root)
return ;
inorder(root->left);
// v2.push_back(root->data);
printf("%d",root->data);
space++;
if(space < n)
printf(" ");
inorder(root->right);
}
int main(){
// printf("hello\n");
memset(hash_table, 1, sizeof(hash_table));
scanf("%d",&n);
for (int i=0; i<n; i++) {
char a,b;
scanf("%*c%c %c",&a,&b);
if (a != '-') {
hash_table[change(a)] = 0;
s[i].right = a-'0';
}else
s[i].right = -1;
if (b != '-') {
hash_table[change(b)] = 0;
s[i].left = b-'0';
}else
s[i].left = -1;
}
int parent = 0;
b_tree root = new Node;
for (int i=0; i<n; i++) {
if (hash_table[i]) {
parent = i;
break;
}
}
root->data = parent;
root->left = root->right = NULL;
complete(root, parent);
space = 0;
layout(root);
space = 0;
printf("\n");
inorder(root);
}