剑指Offer——从上往下打印二叉树

题目描述:

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


分析:

 层次遍历,利用队列的性质,先进先出。

 先将根结点的指针入队。

 如果队列不为空,那么打印队列第一个指针指向的值,如果左子树不为NULL,那么将左子树的指针入队;如果右子树不为NULL,那么将右子树的指针入队。

 重复上一步骤,知道队列为空。


代码:

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

 

posted @ 2017-10-29 11:19  叶建成  阅读(183)  评论(0编辑  收藏  举报