从这里我们开始真正谈到dfs,谈及dfs我们不得不说起最经典的二叉树遍历。。。
这里我们就谈二叉树的中序遍历。。。
从1-n中选出m个数,要求同样的数字不能重复选择,按照字典序正序输出所有方案。
例如:从1到4中选出2个数,共有6种方法,按照字典序输出,依次为:
1 2
1 3
1 4
2 3
2 4
3 4
输入
输入共2个数m, n,中间用空格分隔。(1 <= m <= n <= 20)
输出
按照字典序正序输出所有方案。
数据范围
12% 2 <= n <= 5 1 <= m <= 5
56% 2 <= n <= 15 2 <= m <= 5
100% 2 <= n <= 20 2 <= m <= 17
输入样例
4 2
输出样例
1 2
1 3
1 4
2 3
2 4
3 4
样例解释
从1到4中选出2个数,共有6种方法,按照字典序输出,依次为:
1 2
1 3
1 4
2 3
2 4
3 4
//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
using namespace std;
struct node{
int r;
int l;
int father;
}tree[100086];
int findroot(int x){
if(tree[x].father==0){
return x;
}else{
return findroot(tree[x].father);
}
}
void dfs(int i){
if(tree[i].l!=0){
dfs(tree[i].l);
}
printf("%d\n",i);
if(tree[i].r!=0){
dfs(tree[i].r);
}
}
int main(){
int temp,z;
int fi,si;
cin>>z;
for(int i=1;i<=z;i++){
cin>>fi>>si;
tree[i].l=fi;
tree[i].r=si;
tree[fi].father=i;
tree[si].father=i;
if(fi!=0||si!=0){
temp=i;
}
}
dfs(findroot(temp));
return 0;
}