给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ 9 20
/ 15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
题目链接: 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(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==nullptr) return {};
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> ans;
while(!q.empty()){
int nodeNums = q.size(); // nodeNums是当前层的节点个数
vector<int> nodeInCurLayer; // 存储当前层的节点
for(int i=0; i<nodeNums; i++){
TreeNode* curNode = q.front(); q.pop();
nodeInCurLayer.push_back(curNode->val);
if(curNode->left!=nullptr) q.push(curNode->left);
if(curNode->right!=nullptr) q.push(curNode->right);
}
ans.push_back(nodeInCurLayer);
}
return ans;
}
};
还有一种写法,就是《剑指Offer》里面的写法:
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==nullptr) return {};
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> ans;
int curLayerNodeNums = 1;
int nextLayerNodeNums = 0;
vector<int> nodeInCurLayer;
while(!q.empty()){
TreeNode* curNode = q.front(); q.pop();
nodeInCurLayer.push_back(curNode->val);
curLayerNodeNums--;
if(curNode->left!=nullptr){
q.push(curNode->left);
nextLayerNodeNums++;
}
if(curNode->right!=nullptr){
q.push(curNode->right);
nextLayerNodeNums++;
}
if(curLayerNodeNums==0){
ans.push_back(nodeInCurLayer);
nodeInCurLayer.clear();
curLayerNodeNums = nextLayerNodeNums;
nextLayerNodeNums = 0;
}
}
return ans;
}
};
原文:https://www.cnblogs.com/flix/p/12884883.html