-
Notifications
You must be signed in to change notification settings - Fork 0
/
102. Binary Tree Level Order Traversal.cpp
76 lines (50 loc) · 1.48 KB
/
102. Binary Tree Level Order Traversal.cpp
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
70
71
72
73
74
75
76
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
void breathFirstSearch(TreeNode* node){
queue<TreeNode*> q;
q.push(node);
while(q.size()>0){
TreeNode* cur = q.front();
q.pop();
vector<int> curRow;
if(cur->left){
curRow.push_back(cur->left->val);
q.push(cur->left);
}
if(cur->right){
curRow.push_back(cur->right->val);
q.push(cur->right);
}
result.push_back(curRow);
}
}
vector<vector<int>> levelOrder(TreeNode* root) {
breathFirstSearch(root);
return result;
}
private:
vector<vector<int>> result;
};
int main(){
Solution solution;
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
TreeNode* n2 = new TreeNode(20);
root->right = n2;
n2->left = new TreeNode(15);
n2->right = new TreeNode(7);
vector<vector<int>> answer = solution.levelOrder(root);
return 0;
}