从上往下打印二叉树

 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) return res;
15         queue<TreeNode*> q;
16         q.push(root);
17         while(!q.empty()){
18             TreeNode* node = q.front();
19             q.pop();
20             res.push_back(node->val);
21             if(node->left) q.push(node->left);
22             if(node->right) q.push(node->right);
23         }
24         return res;
25     }
26 };

 

posted @ 2019-07-08 16:30  Austin_anheqiao  阅读(117)  评论(0编辑  收藏  举报