leetcode 102.Binary Tree Level Order Traversal 二叉树的层次遍历

基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行下一个循环就可以了。

C++代码:

 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 class Solution {
11 public:
12     vector<vector<int>> levelOrder(TreeNode* root) {
13         if(root==NULL) return {};
14         queue<TreeNode*> q;
15         TreeNode* front;
16         q.push(root);
17         vector<vector<int>> res;
18         
19         while(!q.empty()){
20             vector<int> onelevel;
21             for(int i=q.size();i>0;i--){
22                 front=q.front();
23                 q.pop();
24                 if(front->left)
25                     q.push(front->left);
26                 if(front->right)
27                     q.push(front->right);
28                 onelevel.push_back(front->val);
29             }
30             res.push_back(onelevel);
31         }
32         return res;
33     }
34 };

 

posted @ 2019-01-29 00:50  Joel_Wang  阅读(167)  评论(0编辑  收藏  举报