给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- vector
int>> levelOrder(TreeNode* root) - {
- queue
q; - vector
int>> v; - if(root==nullptr) {
- return v;
- }
- q.push(root);
- while(!q.empty())//从上到下遍历每一层
- {
- vector<int> level;
- int size=q.size();
- //从左到右遍历一层的所有结点,size是一层的结点总数
- for(int i=0;i
//要使用size而不是q.size(),因为q.size()一直变 - {
- TreeNode* node=q.front();
- q.pop();
- level.push_back(node->val);
- if(node->left)
- q.push(node->left);
- if(node->right)
- q.push(node->right);
- }
- v.push_back(level);
- }
- return v;
- }
- };
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- vector
int>> levelOrder(TreeNode* root) { - vector
int>> result; - int depth = 0;
- order(root, result, depth);
- return result;
- }
- void order(TreeNode* cur, vector
int >>& result, int depth) { - if (cur == nullptr) return;
- if (result.size() == depth) result.push_back(vector<int>());//二叉树顶层按0层来算
- result[depth].push_back(cur->val);
- order(cur->left, result, depth + 1);
- order(cur->right, result, depth + 1);
- }
- };