描述

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
image.png


题解

这道题目,参考评论区helloolleh的代码

  1. /**
  2. * Definition for a binary tree node.
  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<int> levelOrder(TreeNode* root) {
  13. queue<TreeNode*> my_queue;
  14. vector<int> result;
  15. if(root != nullptr) my_queue.push(root);
  16. while(!my_queue.empty()) {
  17. TreeNode* node = my_queue.front();
  18. result.push_back(node->val);
  19. if(node->left) my_queue.push(node->left);
  20. if(node->right) my_queue.push(node->right);
  21. my_queue.pop();
  22. }
  23. return result;
  24. }
  25. };