1102 Invert a Binary Tree(后序遍历反转二叉树)

 大致题意就是给出一个静态二叉树,将其反转后输出层序遍历序列和中序遍历序列。

思路:

使用一维数组存放二叉树的结点,标记输入的孩子结点为已访问,最后可以通过遍历标记数组,找出未被访问的结点即为根结点。

实现反转二叉树的方法:访问完 当前根结点的左孩子和右孩子以后,交换其左、右孩子,后序遍历实现。

层序遍历和中序遍历是模板。

 1 #include<iostream>
 2 #include<queue>
 3 #include<cctype>
 4 #include<algorithm>
 5 using namespace std;
 6 const int maxn = 30;
 7 struct Node {
 8     int lchild;
 9     int rchild;
10 } node[maxn];
11 
12 int n,root;
13 
14 bool notRoot[maxn] = {false};//孩子结点一定不是根结点
15 int getRoot() { //寻找根结点
16     for(int i = 0; i < n; ++i)
17         if(notRoot[i] == false) return i;
18 }
19 
20 void postorder_invertBtree(int root) { //后序遍历,反转二叉树
21     if(root == -1) return ;
22     postorder_invertBtree(node[root].lchild);
23     postorder_invertBtree(node[root].rchild);
24     swap(node[root].lchild,node[root].rchild);
25 }
26 int num = 0;//已访问结点个数
27 void layerorder(int root) { //层序遍历
28     //第一步,定义队列,并入队
29     queue<int> que;
30     que.push(root);
31     //第二步,判断队列是否为空
32     while(!que.empty()) {
33         //第三步,访问队首元素并出队
34         int now = que.front();
35         if(num > 0) printf(" ");
36         printf("%d",now);
37         num++;
38         que.pop();
39         //第四步,下一层元素(左、右孩子)入队
40         if(node[now].lchild != -1) que.push(node[now].lchild);
41         if(node[now].rchild != -1) que.push(node[now].rchild);
42     }
43 }
44 
45 void inorder(int root) { //中序遍历
46     if(root == -1) return ;
47     inorder(node[root].lchild);
48     if(num > 0) printf(" ");
49     printf("%d",root);
50     num++;
51     inorder(node[root].rchild);
52 }
53 int main() {
54     scanf("%d",&n);
55     char lchild,rchild;
56     for(int i = 0; i < n; ++i) {
57         getchar();
58         scanf("%c %c",&lchild,&rchild);
59         node[i].lchild = lchild == '-'? -1:lchild-'0';
60         node[i].rchild = rchild == '-'? -1:rchild-'0';
61         if(lchild != '-')
62             notRoot[node[i].lchild] = true; //标记孩子结点为非根结点
63         if(rchild != '-')
64             notRoot[node[i].rchild] = true;
65     }
66     root = getRoot();
67     postorder_invertBtree(root); //后序遍历,反转二叉树
68     layerorder(root);//层序遍历
69     printf("\n");
70     num = 0; //重置已访问结点的个数 
71     inorder(root);//中序遍历
72     return 0;
73 }

 

 

posted @ 2020-03-02 11:17  tangq123  阅读(228)  评论(0编辑  收藏  举报