首页 > 代码库 > [剑指Offer] 22.从上往下打印二叉树

[剑指Offer] 22.从上往下打印二叉树

【思路】广度优先遍历,队列实现

 1 class Solution
 2 {
 3 public:
 4     vector<int> PrintFromTopToBottom(TreeNode* root)
 5     {
 6         queue<TreeNode*> Queue;
 7         vector<int> res;
 8         if(root == NULL)
 9             return res;
10         Queue.push(root);
11         while(!Queue.empty())
12         {
13             res.push_back(Queue.front()->val);
14             if(Queue.front()->left != NULL)
15                 Queue.push(Queue.front()->left);
16             if(Queue.front()->right != NULL)
17                 Queue.push(Queue.front()->right);
18             Queue.pop();
19         }
20         return res;
21     }
22 };

 

[剑指Offer] 22.从上往下打印二叉树