参考102.binary-tree-level-order-traversal 二叉树的层序遍历,翻转一下结果数组就好了。
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode *root) {
queue<TreeNode *> q;
vector<vector<int>> res;
int depth = 0;
if (root != nullptr)
q.push(root);
while (!q.empty()) {
vector<int> temp;
int size = q.size();
// 如何识别节点在同一层?利用queue的size()来进行处理。
for (int i = 0; i < size; i++) {
TreeNode *node = q.front();
q.pop();
temp.push_back(node->val);
if (node->left != nullptr)
q.push(node->left);
if (node->right != nullptr)
q.push(node->right);
}
res.push_back(temp);
}
std::reverse(res.begin(), res.end());
return res;
}
};
标签:node,binary,level,int,res,二叉树,push,size
From: https://www.cnblogs.com/zwyyy456/p/16608665.html