JZ32 从上往下打印二叉树
描述
不分行从上往下打印出二叉树的每个节点,同层节点从左至右打印。
1
| 例如输入{8,6,10,#,#,2,1},如以下图中的示例二叉树,则依次打印8,6,10,2,1(空节点不打印,跳过),请你将打印的结果存放到一个数组里面,返回。
|

数据范围:
- $0<=节点总数<=1000$
- $-1000<=节点值<=1000 $
示例1
1 2
| 输入:{8,6,10,#,#,2,1} 返回值:[8,6,10,2,1]
|
示例2
1 2
| 输入:{5,4,#,3,#,2,#,1} 返回值:[5,4,3,2,1]
|
题解
初见思路:那还有啥好说的,层序遍历用队列不就得了呗。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <queue> class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector<int> ans; if (!root) return ans;
queue<TreeNode*> q; q.push(root); while(!q.empty()){ TreeNode* curr = q.front(); q.pop(); ans.push_back(curr->val);
if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); }
return ans; } };
|