前言
我们可以利用队列先进先出的特点对我们树进行广度优先遍历。
代码实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| #include <iostream>
#include <queue>
using namespace std;
template<class T>
struct TreeNode {
T val;
TreeNode<T>* left;
TreeNode<T>* right;
TreeNode(T val){
this->val = val;
this->left = nullptr;
this->right = nullptr;
}
};
template<class T>
void BFSTravel(TreeNode<T>* node){
queue<TreeNode<T>*> queue;
queue.push(node);
while (!queue.empty()) {
TreeNode<T>* currentNode = queue.front();
cout<<currentNode->val<<endl;
queue.pop();
if (currentNode->left) {
queue.push(currentNode->left);
}
if(currentNode->right){
queue.push(currentNode->right);
}
}
}
int main(int argc, const char * argv[]) {
TreeNode<int>* root = new TreeNode<int>(10);
TreeNode<int>* node1 = new TreeNode<int>(1);
TreeNode<int>* node2 = new TreeNode<int>(2);
TreeNode<int>* node3 = new TreeNode<int>(3);
TreeNode<int>* node4 = new TreeNode<int>(4);
root->left = node1;
root->right = node3;
node3->left = node2;
node3->right = node4;
BFSTravel(root);
return 0;
}
|