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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
| #include <iostream>
using namespace std;
struct treeNode {
int val;
int position;
treeNode* left;
treeNode* right;
treeNode(int val,int position){
this->val = val;
this->position = position;
this->left = nullptr;
this->right = nullptr;
}
};
class BinaryTree {
int max(int x,int y){
return x>y?x:y;
}
/**
*计算每个结点的深度
**/
int depth(treeNode* node){
if (node==nullptr) {
return 0;
}else{
int leftD = depth(node->left);
int rightD = depth(node->right);
return max(leftD, rightD)+1;
}
}
public:
treeNode* root = nullptr;
/**
*获取深度
**/
int depth(){
return depth(root);
}
/**
* 广度优先遍历
**/
void BFSTravel(){
int dep = depth();
for (int i=0; i<dep; i++) {
printLevel(root, i);
}
}
/**
*打印每一层
**/
void printLevel(treeNode* node, int level){
if (node==nullptr) {
return;
}
if (level==0) {
cout<<node->val<<endl;
}else{
printLevel(node->left, level-1);
printLevel(node->right, level-1);
}
}
};
|