题目描述:
给你一个二叉树,请你返回其按?层序遍历?得到的节点值。 (即逐层地,从左到右访问所有节点)。
代码:
/**
* 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) {
if (!root) return {};
vector<vector<int>> ans;
queue<TreeNode*> nodes;
vector<int> tmp;
TreeNode* ptr = root;
TreeNode* flag = root;
nodes.push(ptr);
while(!nodes.empty()){
ptr = nodes.front();
nodes.pop();
tmp.push_back(ptr->val);
if (ptr->left) nodes.push(ptr->left);
if (ptr->right) nodes.push(ptr->right);
if (ptr == flag){
flag = nodes.back();
ans.push_back(tmp);
tmp.clear();
}
}
return ans;
}
};
?
|