中阶算法---dfs+回溯(2)

从这里我们开始真正谈到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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值