LeetCode题解之Binary Tree Level Order Traversal II

时间:2023-11-11 08:36:14

1、题目描述

LeetCode题解之Binary Tree Level Order Traversal II

2、题目分析

先遍历,再反转。

3、代码

 vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
if (root == NULL)
return ans; queue<TreeNode*> q;
q.push(root);
vector<int> v;
while (!q.empty()) {
int size = q.size();
for (int i = ; i < size; i++) {
TreeNode *node = q.front();
q.pop();
v.push_back(node->val);
if (node->left != NULL)
q.push(node->left); if (node->right != NULL)
q.push(node->right);
}
ans.push_back(v);
v.clear();
} reverse(ans.begin(), ans.end());
return ans;
}