剑指offer (Day1) 从上往下打印二叉树

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

分析:层次遍历(广搜)。

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     vector<int> PrintFromTopToBottom(TreeNode* root) {
13         vector<int> res;
14         if (root == nullptr) {
15             return res;
16         }
17         queue<TreeNode*> que;
18         que.push(root);
19         while(!que.empty()) {
20             TreeNode *tmp = que.front();
21             que.pop();
22             res.push_back(tmp->val);
23             if (tmp->left != nullptr) {
24                 que.push(tmp->left);
25             }
26             if (tmp->right != nullptr) {
27                 que.push(tmp->right);
28             }
29         }
30         return res;
31     }
32 };

猜你喜欢

转载自www.cnblogs.com/qinduanyinghua/p/10474370.html