class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res = {};
TreeNode* curNode = root;
queue<pair<TreeNode*, int>> helper;
if (!root) return res;
helper.push(make_pair(curNode, 0));
while(!helper.empty()){
curNode = helper.front().first;
int i = helper.front().second;
helper.pop();
if (i >= res.size()) res.push_back( vector<int>() );
res[i].push_back(curNode->val);
if (curNode->left) helper.push(make_pair(curNode->left, i+1));
if (curNode->right) helper.push(make_pair(curNode->right, i+1));
}
return res;
}
};

本文介绍了一种使用队列实现的二叉树层次遍历算法,通过将节点及其层级信息一同存储,能够有效地按层级顺序输出二叉树的所有节点值。此方法不仅清晰地展示了二叉树的层次结构,还提供了理解和实现层次遍历的基础。
123

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



