69 lines
1.7 KiB
C++
69 lines
1.7 KiB
C++
/*
|
|
* @Author: e2hang 2099307493@qq.com
|
|
* @Date: 2025-12-10 15:56:43
|
|
* @LastEditors: e2hang 2099307493@qq.com
|
|
* @LastEditTime: 2025-12-10 16:50:18
|
|
* @FilePath: \undefinedd:\code\Git-DataStructureAlgorithms\Exercise\TreeToGraph.cpp
|
|
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
|
|
*/
|
|
#include <iostream>
|
|
#include <vector>
|
|
#include <unordered_map>
|
|
#include <deque>
|
|
using namespace std;
|
|
|
|
struct TreeNode{
|
|
int val;
|
|
TreeNode* left;
|
|
TreeNode* right;
|
|
};
|
|
|
|
//我直接写TreeNode -> Graph的内容了
|
|
unordered_map<TreeNode*, vector<TreeNode*>> adj;
|
|
unordered_map<TreeNode*, bool> visited;
|
|
|
|
void TreeNodeToGraph(TreeNode* root){
|
|
if(root == nullptr) return;
|
|
if(root->left != nullptr){
|
|
adj[root].push_back(root->left);
|
|
adj[root->left].push_back(root);
|
|
TreeNodeToGraph(root->left);
|
|
}
|
|
if(root->right != nullptr){
|
|
adj[root].push_back(root->right);
|
|
adj[root->right].push_back(root);
|
|
TreeNodeToGraph(root->right);
|
|
}
|
|
}
|
|
//target 是 起始点
|
|
deque<TreeNode*> BFS(TreeNode* target, int step){
|
|
deque<TreeNode*> q;
|
|
q.push_back(target);
|
|
int dist = 0;
|
|
|
|
while(!q.empty()){
|
|
int cnt = q.size();//每次弹几个
|
|
if(dist == step) return q;
|
|
|
|
for(int i = 0; i < cnt; i++){
|
|
auto node = q.front();
|
|
q.pop_front();
|
|
visited[node] = true;
|
|
for(auto x : adj[node]){
|
|
if(!visited[x]) {
|
|
q.push_back(x);
|
|
visited[x] = true;
|
|
}
|
|
}
|
|
}
|
|
dist++;
|
|
}
|
|
return {};
|
|
}
|
|
|
|
|
|
int main(){
|
|
|
|
|
|
return 0;
|
|
} |