102.二叉树的层次遍历
题目:给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
二叉树节点定义
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
广度优先遍历模板
void bfs(Node* root) {
map<int, int> visited;
if (!root) return;
queue<Node*> pq;
pq.push(root);
while (!q.empty()) {
Node* tmp = pq.front();
pq.pop();
if (visited.count(tmp->val)) continue;
visited[tmp->val] = 1;
for (int i= 0; i < tmp->children.size(); ++i) {
pq.push(tmp->children[i]);
}
}
return;
}
解法一:层次遍历方法
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode*> pq;
pq.push(root);
while (!pq.empty()) {
int sz = pq.size();
vector<int> path;
for (int i = 0; i < sz; ++i ){
TreeNode* tmp = pq.front();
pq.pop();
path.push_back(tmp->val);
if (tmp->left != nullptr) pq.push(tmp->left);
if (tmp->right != nullptr) pq.push(tmp->right);
}
res.push_back(path);
}
return res;
}
};
解法二:前序遍历方法
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return {};
vector<vector<int>> res;
helper(res, root, 0);
return res;
}
void helper(vector<vector<int>>& res, TreeNode* root, int depth){
if (!root) return;
if (res.size() == depth){
res.push_back(vector<int>{});
}
res[depth].push_back(root->val);
helper(res, root->left, depth+1);
helper(res, root->right, depth+1);
}
};