给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
分析:
队列层次遍历
/**
* 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) {
vector<vector<int>> v;
if(NULL == root)
return v;
// 层次遍历需要用一个队列
queue<TreeNode*> q;
q.push(root);
// 不空则循环
while(!q.empty()){
// 当前层节点个数
int num = q.size();
vector<int> ve;
for(int i=0;i<num;i++){
TreeNode *temp = q.front();
q.pop();
ve.push_back(temp->val);
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
v.push_back(ve);
}
return v;
}
};
本文介绍了一种算法,用于解决二叉树的层次遍历问题。通过使用队列进行层次遍历,逐层地从左到右访问所有节点,最终返回每层的节点值。该算法适用于计算机科学和数据结构领域。
472

被折叠的 条评论
为什么被折叠?



