地址 https://www.acwing.com/problem/content/description/41/
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null] 8 / 12 2 / 6 / 4 输出:[8, 12, 2, 6, 4]
bfs典型例题
/** * 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> res; queue<TreeNode* > que; void bfs() { while(!que.empty()){ TreeNode* p = que.front(); que.pop(); res.push_back(p->val); if(p->left != NULL) que.push(p->left); if(p->right != NULL) que.push(p->right); } } vector<int> printFromTopToBottom(TreeNode* root) { if(root == NULL) return res; que.push(root); bfs(); return res; } };