-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Level_Order_Traversal2.cpp
More file actions
70 lines (65 loc) · 2.22 KB
/
Binary_Tree_Level_Order_Traversal2.cpp
File metadata and controls
70 lines (65 loc) · 2.22 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//O(N)
//O(N)
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
vector<int> row;
queue<TreeNode*> currQ;
int currNum = 1, nextNum = 0;
if (root) currQ.push(root);
while (!currQ.empty()) {
TreeNode* front = currQ.front();
currQ.pop(), currNum--;
row.push_back(front->val);
if (front->left) currQ.push(front->left), nextNum++;
if (front->right) currQ.push(front->right), nextNum++;
if (currNum == 0) {
res.push_back(row);
row.clear();
currNum = nextNum;
nextNum = 0;
}
}
reverse(res.begin(),res.end());
return res;
}
vector<vector<int> > levelOrderBottom2(TreeNode *root)
{
vector<vector<int> > res;
if (!root) return res;
stack<vector<TreeNode*> > stk;
stk.push(vector<TreeNode*>(1, root));
while(true)
{
vector<TreeNode*> row;
for (vector<TreeNode*>::iterator it = stk.top().begin(); it != stk.top().end(); ++it)
{
if ((*it)->left) row.push_back((*it)->left);
if ((*it)->right) row.push_back((*it)->right);
}
if (row.empty()) break;
stk.push(row);
}
while (!stk.empty())
{
vector<int> row;
for (vector<TreeNode*>::iterator it = stk.top().begin(); it != stk.top().end(); ++it)
row.push_back((*it)->val);
res.push_back(row);
stk.pop();
}
return res;
}
};