树的层级划分 leetcode102

Posted jkserge

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树的层级划分 leetcode102相关的知识,希望对你有一定的参考价值。

 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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode(144,94,145,102)中迭代版的二叉树的前中后层级遍历

LeetCode-102-二叉树的遍历

Leetcode102. 二叉树的层序遍历(经典dfs)

LeetCode第102题—二叉树的层序遍历—Python实现

python-leetcode102-树的宽度遍历二叉树的层次遍历

leetcode102二叉树的层序遍历