102. 二叉树的层序遍历

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 
11 class Solution 
12 {
13 vector<vector<int>> res;
14 public:
15     vector<vector<int>> levelOrder(TreeNode* root) 
16     {
17         if(root == NULL) return res;
18         queue<TreeNode*> q;
19         q.push(root);
20         while(!q.empty())
21         {
22             int n = q.size();
23             vector<int> vec;
24             for(int i = 0;i < n;i ++)
25             {
26                 TreeNode* temp = q.front(),q.pop();
27                 if(temp->left) q.push(temp->left);
28                 if(temp->right)q.push(temp->right);
29 
30                 vec.push_back(temp->val);
31             }
32             res.push_back(vec);
33         }
34         return res;
35     }
36 };

 

posted @ 2020-03-23 17:36  Jinxiaobo0509  阅读(132)  评论(0)    收藏  举报