C++

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. vector<vector<int>> levelOrder(TreeNode* root) {
  15. if(root == nullptr)
  16. {
  17. return {};
  18. }
  19. //建立一个队列
  20. queue<TreeNode *> q;
  21. q.push(root);
  22. //保存结果
  23. vector<vector<int>> ret;
  24. //队列不空
  25. while(!q.empty())
  26. {
  27. //保存当前层的结果
  28. vector<int> currentLayer;
  29. int currentSize = q.size();
  30. //遍历当前层
  31. for(int i = 0; i < currentSize; i++)
  32. {
  33. //弹出当前节点的值
  34. TreeNode* current = q.front();
  35. q.pop();
  36. //加入当前节点的值
  37. currentLayer.push_back(current->val);
  38. //左右子树加入队列
  39. if(current->left) q.push(current->left);
  40. if(current->right) q.push(current->right);
  41. }
  42. ret.push_back(currentLayer);
  43. }
  44. return ret;
  45. }
  46. };

上述代码中第33行在之前的错误提交中写的是for(int i = 0; i < q.size(); i++)导致结果输出错误,
原因分析:因为每次左右子树不空的时候都会加入左右子树,此时再去判断q.size()其实是一个动态变化的值,有潜在的风险