剑指offer——32从上到下打印二叉树

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 
题解:
  就是简单的层序遍历
  
 1 class Solution {
 2 public:
 3     vector<int> PrintFromTopToBottom(TreeNode* root) {
 4         vector<int>res;
 5         BFS(root, res);
 6         return res;
 7     }
 8     void BFS(TreeNode *root, vector<int>&res)
 9     {
10         if (root == nullptr)return;
11         queue<TreeNode*>q;
12         q.push(root);
13         while (!q.empty())
14         {
15             TreeNode* p = q.front();
16             q.pop();
17             res.push_back(p->val);
18             if (p->left != nullptr)q.push(p->left);
19             if (p->right != nullptr)q.push(p->right);
20         }
21     }
22 };

 

posted @ 2019-10-15 22:27  自由之翼Az  阅读(158)  评论(0编辑  收藏  举报