Examples of how to search in tree structure 3 are Shared

  • 2020-04-02 02:11:47
  • OfStack



#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int M = 20;
int n, m;
int ans[M];
//Binary tree
void dfs_two(int cur){
 if(cur == n){
  for(int i = 0; i < n; i++){
   cout << ans[i] << " ";
  }
  cout << endl;
  return;
 }
 ans[cur] = 1;
 dfs_two(cur + 1);
 ans[cur] = 0;
 dfs_two(cur + 1);
}
//M tree
void dfs_m(int cur){
 if(cur == n){
  for(int i = 0; i < n; i++){
   cout << ans[i] << " ";
  }
  cout << endl;
  return ;
 }
 for(int i =0; i < n; i++){
  ans[cur] = i;
  dfs_m(cur + 1);
 }
}
bool vis[M];
//A subset of the tree
void dfs_sub(int cur){
 if(cur == n){
  for(int i = 0; i < n; i++){
   cout << ans[i] << " ";
  }
  cout << endl;
  return;
 }
 for(int i = 0; i < n; i++){
  if(false == vis[i]){
   vis[i] = true;
   ans[cur] = i;
   dfs_sub(cur + 1);
   vis[i] = false;
  }
 }
}
int main(){
 n = 5;
 memset(ans, -1, sizeof(ans));
 memset(vis, false, sizeof(vis));
 dfs_two(0);//Binary tree search 
 dfs_m(0);// full M tree search 
 dfs_sub(0);//A subset of the tree search 
 return 0;
}


Related articles: