码迷,mamicode.com
首页 > 其他好文 > 详细

树的层级划分 leetcode102

时间:2018-07-18 00:34:54      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:front   nbsp   int   col   mil   order   需要   empty   turn   

 1 class Solution {
 2 public:
 3     vector<vector<int>> levelOrder(TreeNode* root) {
 4         vector<vector<int>> ret;
 5         if (!root) return ret;
 6         queue<TreeNode*> q;
 7         q.push(root);
 8         int lvl = 1;
 9         int num = 1;
10         int next = 0;
11         int i = 0;
12         TreeNode* node = q.front();
13         while(!q.empty()) {
14             if (ret.size() < lvl) ret.resize(lvl);
15             q.pop();
16             ++i;
17             ret[lvl-1].push_back(node->val);
18             if (node->left) {
19                 ++next;
20                 q.push(node->left);
21             }
22             if (node->right) {
23                 ++next;
24                 q.push(node->right);
25             }
26             
27             if (i == num) {
28                 ++lvl;
29                 num = next;
30                 i = 0;
31                 next = 0;
32             }
33             node = q.front();
34         }
35         return ret;
36     }
37 };

 

需要保存:本层遍历的个数,下层添加的个数,本层遍历位置,层级

树的层级划分 leetcode102

标签:front   nbsp   int   col   mil   order   需要   empty   turn   

原文地址:https://www.cnblogs.com/jkserge/p/9326760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!