Home PAT 1102 Invert a Binary Tree
Post
Cancel

PAT 1102 Invert a Binary Tree

Link

树的层次遍历和中序遍历. 代码中给出了中序遍历的递归和非递归写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <cmath>
#include <cctype>
#include <queue>
using namespace std;
int n;
struct node{
    int left=-1,right=-1;
}a[15];
bool v[15];
bool flag=false;
void BFS(int root){
    queue<int>q;
    printf("%d",root);
    if(a[root].left!=-1) q.push(a[root].left);
    if(a[root].right!=-1) q.push(a[root].right);
    while(!q.empty()){
        root=q.front();
        printf(" %d",root);
        q.pop();
        if(a[root].left!=-1) q.push(a[root].left);
        if(a[root].right!=-1) q.push(a[root].right);
    }
    printf("\n");
}
//递归
void InOrder(int root){
    if(root==-1) return;
    InOrder(a[root].left);
    if(flag) printf(" ");
    else flag=true;
    printf("%d",root);
    InOrder(a[root].right);
}
//非递归
void inOrder(int x){
	stack<int>st;
	bool flag=true;
	while(x!=-1||!st.empty()){
		if(x!=-1){
			st.push(x);
			x=lch[x];
		}else{
			x=st.top();
			st.pop();
			if(flag){cout<<x;flag=false;}
			else cout<<" "<<x;
			x=rch[x];
		}
	}
	cout<<endl;
}
int main() {
    scanf("%d",&n);
    for(int i=0;i<n;++i){
        char ch1,ch2;
        cin>>ch1>>ch2;
        if(isdigit(ch1)){
            a[i].right=ch1-'0';
            v[a[i].right]=true;
        }
        if(isdigit(ch2)){
            a[i].left=ch2-'0';
            v[a[i].left]=true;
        }
    }
    int root=0;
    for(int i=0;i<n;++i)
        if(!v[i]){
            root=i;
            break;
        }
    BFS(root);
    InOrder(root);
    return 0;
}
This post is licensed under CC BY 4.0 by the author.