剑指Offer-22-从上往下打印二叉树

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

Code

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
//思路二叉树的层序遍历
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> res;//结果集
if(!root)
return res;
TreeNode* temp = root;
queue<TreeNode*> q;

q.push(temp);
while(!q.empty()){
temp = q.front();
res.push_back(temp->val);
q.pop();
if(temp->left!=NULL)
q.push(temp->left);
if(temp->right!=NULL)
q.push(temp->right);
}
return res;
}
};

----\(˙<>˙)/----赞赏一下吧~