樹形結(jié)構(gòu)的3中搜索方式示例分享
/**
樹的3中常見搜索方式
1.二叉樹方式(每一層只有0和1)
2.滿m叉樹(每一層都有0 到m - 1)
3.子集樹,也稱為全排列樹
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int M = 20;
int n, m;
int ans[M];
//二叉樹
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叉樹
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];
//子集樹
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);//二叉樹搜索
dfs_m(0);//滿m叉樹搜索
dfs_sub(0);//子集樹搜索
return 0;
}
相關(guān)文章
C++使用數(shù)組來實(shí)現(xiàn)哈夫曼樹
給定N個權(quán)值作為N個葉子結(jié)點(diǎn),構(gòu)造一棵二叉樹,若該樹的帶權(quán)路徑長度達(dá)到最小,稱這樣的二叉樹為最優(yōu)二叉樹,也稱為哈夫曼樹(Huffman?Tree)。哈夫曼樹是帶權(quán)路徑長度最短的樹,權(quán)值較大的結(jié)點(diǎn)離根較近2022-05-05
C++實(shí)現(xiàn)LeetCode(202.快樂數(shù))
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(202.快樂數(shù)),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
C/C++實(shí)現(xiàn)動態(tài)庫動態(tài)加載
在很多項(xiàng)目中,我們多少會用到第三方動態(tài)庫,這些動態(tài)庫一般都是相對固定,使用也很簡單,下面我們就來看看c/c++中如何實(shí)現(xiàn)動態(tài)庫動態(tài)加載吧2024-01-01

