-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
99 lines (93 loc) · 2.14 KB
/
main.cpp
File metadata and controls
99 lines (93 loc) · 2.14 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL) return res;
vector<int> tmp;
queue<TreeNode*> qu;
qu.push(root);
int len = 1;
while(!qu.empty())
{
TreeNode* top = qu.front();
qu.pop();
tmp.push_back(top->val);
if(top -> left)
qu.push(top->left);
if(top -> right)
qu.push(top->right);
if(--len == 0)
{
res.push_back(tmp);
tmp.clear();
len = qu.size();
}
}
return res;
}
};
/*
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
dfs(root, 0, res);
return res;
}
void dfs(TreeNode* root, int depth, vector<vector<int>> &res)
{
if(root == NULL)
return ;
if(res.size() == depth)
res.push_back(vector<int>());
res[depth].push_back(root->val);
dfs(root->left, depth+1, res);
dfs(root->right, depth+1, res);
}
};
*/
// 使用两个队列
/*
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL) return res;
queue<TreeNode *> qu;
vector<int> tmp;
queue<TreeNode *> nodes;
qu.push(root);
while(!qu.empty())
{
TreeNode *top = qu.front();
tmp.push_back(top->val);
qu.pop();
if(top -> left)
nodes.push(top->left);
if(top -> right)
nodes.push(top->right);
if(qu.empty())
{
qu.swap(nodes);
res.push_back(tmp);
tmp.clear();
}
}
return res;
}
};
*/
int main()
{
return 0;
}