-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Level Order Traversal.cpp
More file actions
44 lines (42 loc) · 1.17 KB
/
Binary Tree Level Order Traversal.cpp
File metadata and controls
44 lines (42 loc) · 1.17 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
/**
* Definition for a binary tree node.
* 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>> result;
vector<int> level;
queue<TreeNode *> stack,next;
TreeNode* p = nullptr;
// int level = 0;
if (root == NULL){
return result;
}
stack.push(root);
while(!stack.empty()){
while(!stack.empty())
{
p=stack.front();
stack.pop();
level.push_back(p->val);
if(p->left != NULL){
next.push(p->left);
}
if(p->right != NULL){
next.push(p->right);
}
}
result.push_back(level);
level.clear();
swap(next,stack);
}
return result;
}
};
其实本质是层次遍历,这是非递归的做法,借助两个队列一个数组