从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
返回:[3,9,20,15,7]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题我们的思路就是层序遍历整棵二叉树,然后将遍历中每一个结点对应的val保存到我们的结果容器中。并最后返回我们的结果容器
与层序遍历相关的知识请参考
就是我们用一个队列保存我们二叉树的根结点,只要队列不为空,我们每次都从队列的队首取出一个结点,并且将这个结点的左右结点(非nullptr)的入队列,以此循环,知道队列中没有元素。
- /**
- * 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) {
- if(root==nullptr)
- {
- return result;
- }
- tmp.push(root);
- while(tmp.empty()!=true)
- {
- TreeNode *node=tmp.front();
- result.push_back(node->val);
- if(node->left!=nullptr)
- {
- tmp.push(node->left);
- }
- if(node->right!=nullptr)
- {
- tmp.push(node->right);
- }
- tmp.pop();
- }
- return result;
- }
- private:
- vector<int> result;
- queue
tmp; - };