题目要求:
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
返回其层序遍历结果:[
[3],
[9,20],
[15,7]
]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal
解题代码:
//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<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if (root == NULL) return res; queue<pair<TreeNode*, int>> q; // int是层数 q.push(make_pair(root, 0)); while (!q.empty()) { TreeNode* node = q.front().first; int level = q.front().second; q.pop(); if (level == res.size()) res.push_back(vector<int>()); res[level].push_back(node->val); if (node->left) q.push(make_pair(node->left, level + 1)); if (node->right) q.push(make_pair(node->right, level + 1)); } return res; } };