树的层次遍历

题目

LeetCode102.二叉树的层序遍历

代码

 1 class Solution {
 2 public:
 3     
 4     vector<vector<int>>ans;
 5     vector<vector<int>> levelOrder(TreeNode* root) {
 6         if(root == NULL ) return ans;
 7         queue<TreeNode*>q;
 8         q.push(root);
 9         while(!q.empty()){
10             int sum = q.size();
11             vector<int>path;
12             for(int i = 0;i < sum;i++){ //控制当前层全部弹出
13                 auto t = q.front();path.push_back(t->val);
14                 q.pop();
15                 if(t->left!=NULL) {q.push(t->left);}
16                 if(t->right!=NULL) {q.push(t->right);}
17             }
18             ans.push_back(path); 
19         } 
20         return ans;
21     }
22 };

题目

LeetCode199. 二叉树的右视图

代码

 1 class Solution {
 2 public:
 3     vector<int>ans;
 4     vector<int> rightSideView(TreeNode* root) {
 5         if(root==NULL) return ans;
 6         queue<TreeNode*>q;
 7         q.push(root);
 8         while(!q.empty()){
 9             int sum = q.size();
10             TreeNode* t;
11             for(int i = 0;i < sum;i++){
12                 t = q.front();q.pop();
13                 if(t->left!=NULL) q.push(t->left);
14                 if(t->right!=NULL) q.push(t->right);
15             }
16             ans.push_back(t->val);
17         }
18         return ans;
19     }
20 };

题目

LeetCode429. N 叉树的层序遍历

代码

 1 class Solution {
 2 public:
 3     vector<vector<int>>ans;
 4     vector<vector<int>> levelOrder(Node* root) {
 5         if(root == NULL) return ans;
 6         queue<Node*>q;
 7         q.push(root);
 8         while(!q.empty()){
 9             int sum = q.size();
10             vector<int>path;
11             for(int i = 0;i < sum;i++){
12                 auto t = q.front();q.pop();path.push_back(t->val);
13                 for(int i = 0;i < t->children.size();i++){
14                     if(t->children[i] != NULL) q.push(t->children[i]);
15                 }
16             }
17             ans.push_back(path);
18         }
19         return ans;
20     }
21 };
原文地址:https://www.cnblogs.com/fresh-coder/p/14443788.html