剑指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 {
11 public:
12     vector<vector<int> > Print(TreeNode* root) {
13         vector<vector<int> > res;
14         vector<int> v;
15         if (root == NULL)
16             return res;
17         TreeNode* temp;
18         queue<TreeNode*> q;
19         q.push(root);
20         while(!q.empty()) {
21             v.clear();
22             int len = q.size(); //队列中的元素个数即为当前行的所有元素
23             v.resize(len, 0);
24             for (int i = 0; i < len; i++) {
25                 temp = q.front();
26                 q.pop();
27                 v[i] = temp->val;
28                 if (temp->left != NULL)
29                     q.push(temp->left);
30                 if (temp->right != NULL)
31                     q.push(temp->right);
32             }
33             res.push_back(v);
34         }
35     }
36 };

猜你喜欢

转载自www.cnblogs.com/qinduanyinghua/p/11327067.html