二叉树的层序遍历
给你二叉树的根节点
root
,返回其节点值的
层序遍历。 (即逐层地,从左到右访问所有节点)。
提示:
- 树中节点数目在范围 [0, 2000] 内
- -1000 <=
Node.val
<= 1000
题解1 迭代——BFS
/**
* 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>>();
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> res;
while(q.size()){
int l_s = q.size();
vector<int> kk;
while(l_s){
TreeNode* tmp = q.front();
q.pop();
kk.emplace_back(tmp->val);
if(tmp->left)
q.push(tmp->left);
if(tmp->right)
q.push(tmp->right);
l_s --;
}
res.emplace_back(kk);
}
return res;
}
};
题解2 递归——DFS
class Solution {
public:
vector<vector<int>> ret;
void level(TreeNode* root, int lev) {
if(!root) return;
if (lev >= ret.size()) {
ret.push_back(vector<int>());
}
ret[lev].push_back(root -> val);
level(root -> left, lev + 1);
level(root -> right, lev + 1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
level(root, 0);
return ret;
}
};