-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path107. Binary Tree Level Order Traversal II.cpp
46 lines (45 loc) · 1.33 KB
/
107. Binary Tree Level Order Traversal II.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
/**
11:28 - 11:32
Copy code from 102,
call levelOrder and reverse the outer side of ans.
*/
/**
* Definition for a binary tree node.
* 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 {
private:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>>ans;
if(root==nullptr)return ans;
queue<TreeNode*>curLevel,nextLevel;
curLevel.push(root);
while(!curLevel.empty()) {
vector<int>curNodes;
queue<TreeNode*>nextLevel;
while(!curLevel.empty()) {
TreeNode* cur = curLevel.front();
curLevel.pop();
curNodes.push_back(cur->val);
if(cur->left)nextLevel.push(cur->left);
if(cur->right)nextLevel.push(cur->right);
}
ans.push_back(curNodes);
curLevel = nextLevel;
}
return ans;
}
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans=levelOrder(root);
reverse(ans.begin(), ans.end());
return ans;
}
};