3 of the tree structure search method sample share _c language

Source: Internet
Author: User

Copy Code code as follows:

/**
Common search methods in 3 of trees
1. Two fork tree (only 0 and 1 per layer)
2. Full m fork tree (each layer has 0 to m-1)
3. Subset trees, also called all-ranked trees
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>

using namespace Std;

const int M = 20;

int n, m;
Int ans[m];
//Two fork tree
void dfs_two (int cur) {
 if (cur = = N) {
  for (int i = 0; i < n; i++) {
  & Nbsp;cout << Ans[i] << "";
  }
  cout << Endl;
  return;
 }
 ans[cur] = 1;
 dfs_two (cur + 1);
 ans[cur] = 0;
 dfs_two (cur + 1);
}

M Fork 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];
Subset 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);//two fork Tree Search
Dfs_m (0)/full m fork Tree search
Dfs_sub (0);//subset Tree Search
return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.