二叉树的递归遍历
概述
对于二叉树T,可以递归遍历它的先序遍历,中序遍历和后序遍历。
PreOrder(T)=T的根结点+PreOrder(T的左子树)+PreOrder(T的右子树)
InOrder(T) = InOrder(T的左子树)+T的根结点+InOrder(T的右子树)
PostOrder(T) = PostOrder(T的左子树)+PostOrder(T的右子树)+根结点
这三种都属于递归遍历,或者说深度优先遍历。(DFS)
天平
给一个树状天平,根据力矩相等原则判断是否平衡,所谓力矩相等,就是Wl*Dl = Wr*Dr,其中Wl和Wr分别为两边砝码的重量,D为距离。
采用递归先序遍历的方式输入:每个天平的输入格式为Wl,Dl,Wr,Dr;当Wl或Wr为0时,表示该“砝码”实际是一个子天平,接下来会描述这个子天平。当Wl=Wr=0时,会先描述左子天平,然后是右子天平。
Input:
1
0 2 0 4
0 3 0 1
1 1 1 1
2 4 4 2
1 6 3 2
Output:
YES
问题分析
这道题的输入就采取了递归方式定义,因此可以直接编写一个递归输入过程,在输入过程中就可以直接判断。
解题代码
#include<bits/stdc++.h>
using namespace std;
int W;
//返回子天平是否平衡,W为子天平的总重量
int solve(int W){
int W1,D1,W2,D2;
cin>>W1>>D1>>W2>>D2;
int b1 = 1,b2 = 1;
if(!W1){
b1 = solve(W1);
}
if(!W2){
b2 = solve(W2);
}
W = W1 + W2;
return b1&b2&(W1*D1 == W2*D2);
}
int main(){
int T;
cin>>T;
while(T--){
if(solve(W))
cout<<"YES"<<endl;
else{
cout<<"NO"<<endl;
}
if(T){
cout<<endl;
}
}
return 0;
}
下落的树叶
给一颗二叉树,每一个结点都有一个水平位置:左子节点在他左边一个单位,右字结点在右边一个单位。从左到右输出每一个水平位置的所有结点的权值之和。按照先序递归的方式输入,用-1表示空树。
Input
5 7 -1 6 -1 -1 3 -1 -1
8 2 9 -1 -1 6 5 -1 -1 12 -1 -1 3 7 -1 -1 -1
-1
Output
Case 1:
7 11 3
Case 2:
9 7 21 15
这题与上题相似,直接先序遍历,在遍历过程中求出水平位置之和
解题代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
int sum[N];
//输入并统计一棵子树,树根的水平位置为p
void build(int p){
int v;
cin>>v;
if(v == -1){
return;
}
sum[p] += v;
build(p-1);
build(p+1);
}
int init(){
int v;cin>>v;
if(v == -1){
return 0;
}
memset(sum,0,sizeof(sum));
int pos = N/2;
//树根的水平位置
sum[pos] = v;
build(pos-1);
build(pos+1);
}
int main(){
int k = 0;
while(init()){
int p = 0;
//找到最左边的叶子
while(sum[p] == 0){
p++;
}
cout<<"Case "<<++k<<":\n"<<sum[p++];
while(sum[p] != 0){
cout<<" "<<sum[p++];
}
cout<<endl<<endl;
}
return 0;
}
非二叉树
四分树
2 1
3 4
可以用四分树来表示一个黑白图像。方法是用根结点来表示整幅图像,然后把行列分成两等分,按照图中的方式编号,从左到右对应4个字结点。如果某个子结点对应的区域全黑或者全白,则直接用一个黑结点(f)或者白结点(e)表示。如果既有黑又有白,则用一个灰结点(p)表示,并且为这个区域递归建树。
给出两棵四分树的先序遍历,求两者合并之后(黑色合并)黑色像素的个数。p表示中间结点。
Input
3
ppeeefpffeefe
pefepeefe
peeef
peefe
peeef
peepefefe
Output
There are 640 black pixels.
There are 512 black pixels.
There are 384 black pixels.
因为四分树先序遍历后可以直接确定这棵树,那么直接在遍历过程中统计即可
解题代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1024+10;
const int len = 32;
char s[N];
int buf[len][len],cnt;
void build(const char* s,int &p,int r,int c,int w){
char ch = s[p++];
if(ch == 'p'){
build(s,p,r,c+w/2,w/2); //1
build(s,p,r,c,w/2); //2
build(s,p,r+w/2,c,w/2); //3
build(s,p,r+w/2,c+w/2,w/2); //4
}
//画黑像素
else if(ch == 'f'){
for(int i = r;i < r+w;i++){
for(int j = c;j < c+w;j++){
if(buf[i][j] == 0){
buf[i][j] = 1;
cnt++;
}
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin>>T;
while(T--){
memset(buf,0,sizeof(buf));
cnt = 0;
for(int i = 0;i < 2;i++){
cin>>s;
int p = 0;
build(s,p,0,0,len);
}
cout<<"There are "<<cnt<<" black pixels."<<endl;
}
return 0;
}