基础遍历预热
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
};
// 前序遍历 递归
class SolutionRecursive {
public:
void traverse(TreeNode* cur, vector<int>& vec) {
if (cur == nullptr) {
return;
}
vec.push_back(cur->val);
traverse(cur->right, vec);
traverse(cur->left, vec);
}
vector<int> preOrderTraveral(TreeNode* root) {
vector<int> result;
traverse(root, result);
return result;
}
};
// 前序遍历 迭代
class SolutionIter {
vector<int> preOrderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if (root == nullptr) {
return result;
}
st.push(root);
while( !st.empty()) {
TreeNode* Node = st.top();
st.pop();
result.push_back(Node->val); // 根
if (Node->right) {
st.push(Node->right); // 左
}
if (Node->left) {
st.push(Node->left); // 右
}
}
return result;
}
};
// 后续遍历 迭代, 左、右、根
class Solution {
public:
vector<int> PostOrderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if (root == nullptr) {
return result;
}
st.push(root);
while (!st.empty()) {
TreeNode* Node = st.top();
st.pop();
result.push_back(Node->val);
if (Node->left) {
st.push(Node->left);
}
if (Node->right) {
st.push(Node->right);
}
}
reverse(result.begin(), result.end());
return result;
}
};
BFS热身(二叉树)
#include <queue>
#include <vector>
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) {
return {};
}
queue<TreeNode*> que;
if (root != nullptr) {
que.push(root);
}
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size();
vector<int> vec;
for (int i = 0; i < size; i++) {
TreeNode* Node = que.front();
que.pop();
vec.push_back(Node->val);
if (Node->left) {
que.push(Node->left);
}
if (Node -> right) {
que.push(Node->right);
}
}
result.push_back(vec);
}
return result;
}
};
正式上菜,有向图中2个节点
C++ BFS(图 遍历)
path between two vertices in directed graph
#include <iostream>
#include <list>
using namespace std;
class Graph {
int V;
list<int> *adj;
public:
Graph(int V);
void addEdge(int v, int w); // function to add an edge to graph
bool isReachable(int s, int d);
};
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
}
// use bfs to write code
bool Graph::isReachable(int s, int d) {
if (s == d)
return true;
// 存储节点状态 visited, list -> queue
// 遍历 iterator
// 某个节点bfs,判断是否出现另一个节点
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
list<int> queue;
queue.push_back(s);
list<int>::iterator i;
while (!queue.empty()) {
s = queue.front();
queue.pop_front();
for (i = adj[s].begin(); i != adj[s].end(); i++) {
if (*i == d)
return true;
// 考虑是否visited
if (!visited[*i]) {
visited[*i] = true;
queue.push_back(*i);
}
}
}
return false;
}
path true: 1 to 3
path false: 3 to 1
python
# 有向图中的2节点是否联通问题
from collections import defaultdict
class Graph:
"""
这里比较粗暴的认为,0, 1, 2, 3, 默认为node节点,实际场景中有些不妥
"""
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def isReachable(self, s, d):
visited = [False] * self.V
queue = []
visited[s] = True
queue.append(s)
while queue:
node = queue.pop(0)
if node == d:
return True
for j in self.graph[node]:
if visited[j] == False:
visited[j] = True
queue.append(j)
return False
if __name__ == "__main__":
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
u = 1
v = 3
if g.isReachable(u, v):
print("There is a path from %d to %d" % (u, v))
else:
print("There is no path from %d to %d" % (u, v))
u = 3
v = 1
if g.isReachable(u, v):
print("There is a path from %d to %d" % (u, v))
else:
print("There is no path from %d to %d" % (u, v))
# There is a path from 1 to 3
# There is no path from 3 to 1