Skip to content

Commit 80dc18a

Browse files
committed
2
1 parent 145cc0c commit 80dc18a

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
vector<vector<int> > levelOrderBottom(TreeNode *root) {
13+
// Start typing your C/C++ solution below
14+
// DO NOT write int main() function
15+
16+
vector<vector<int>> result;
17+
if (root == NULL) return result;
18+
19+
queue<TreeNode*> nodeQueue;
20+
vector<int> value;
21+
nodeQueue.push(root);
22+
int nodeNow = 1;
23+
int nodeNext = 0;
24+
25+
while (!nodeQueue.empty()) {
26+
TreeNode *node = nodeQueue.front();
27+
nodeQueue.pop();
28+
nodeNow -= 1;
29+
value.push_back(node->val);
30+
if (node->left) {
31+
nodeQueue.push(node->left);
32+
nodeNext += 1;
33+
}
34+
if (node->right) {
35+
nodeQueue.push(node->right);
36+
nodeNext += 1;
37+
}
38+
if (nodeNow == 0) {
39+
result.push_back(value);
40+
value.clear();
41+
nodeNow = nodeNext;
42+
nodeNext = 0;
43+
}
44+
}
45+
reverse(result.begin(), result.end());
46+
return move(result);
47+
}
48+
};

0 commit comments

Comments
 (0)