22.从上往下打印二叉树——剑指offer

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 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 {//利用queue实现广度优先遍历
11 public:
12     vector<int> PrintFromTopToBottom(TreeNode* root) {
13         vector<int> res;
14         queue<TreeNode*> temp;
15         if(root!=nullptr) temp.push(root);
16         while(!temp.empty()){
17             res.push_back(temp.front()->val);
18            if(temp.front()->left) temp.push(temp.front()->left);
19                if(temp.front()->right) temp.push(temp.front()->right);
20             temp.pop();
21         }
22         return res;
23     }
24 };

 

posted @ 2019-05-19 17:38  unique_ptr  阅读(78)  评论(0编辑  收藏  举报