今日份题目:
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
示例
给定二叉树: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回:
[3,9,20,15,7]
提示
-
节点总数 <= 1000
题目思路
使用BFS广度优先遍历对树进行层次遍历。BFS的精髓,我认为,在于对queue队列的使用,每次从队列中取出节点并将当前节点内容加入结果vector中,然后从左到右将需要遍历的节点放入queue队列,直到队列中节点为空。
代码
/**
* 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)
{
vector<int> ans;
if(root==NULL) return {};
queue<TreeNode*> p;
//BFS
ans.push_back(root->val);
if(root->left) p.push(root->left);
if(root->right) p.push(root->right);
//以上三句也可以写成p.push(root);
while(!p.empty())
{
TreeNode* cur=p.front();
p.pop();
ans.push_back(cur->val);
if(cur->left) p.push(cur->left);
if(cur->right) p.push(cur->right);
}
return ans;
}
};
提交结果
欢迎大家在评论区讨论,如有不懂的代码部分,欢迎在评论区留言!