描述
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
题解
这道题目,参考评论区helloolleh的代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
queue<TreeNode*> my_queue;
vector<int> result;
if(root != nullptr) my_queue.push(root);
while(!my_queue.empty()) {
TreeNode* node = my_queue.front();
result.push_back(node->val);
if(node->left) my_queue.push(node->left);
if(node->right) my_queue.push(node->right);
my_queue.pop();
}
return result;
}
};