102. 二叉树的层次遍历
程序员文章站
2022-03-03 10:35:17
...
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树:[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
dfs解法:
class Solution {
public:
void dfs(TreeNode *root,int level,vector<vector<int>> &res)
{
if(!root) return ;
if(level+1>res.size()) res.push_back({});
res[level].push_back(root->val);
dfs(root->left,level+1,res);
dfs(root->right,level+1,res);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
dfs(root,0,res);
return res;
}
};
bfs解法:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
TreeNode* right=root,*nextright=NULL;
queue<TreeNode*> Q;
if(root) Q.push(root);
vector<vector<int>> vv;
vv.push_back(vector<int>());
while(!Q.empty()){
TreeNode* cur=Q.front();Q.pop();
vv.back().push_back(cur->val);
if(cur->left){Q.push(cur->left);nextright=cur->left;}
if(cur->right){Q.push(cur->right);nextright=cur->right;}
if(cur == right){
right=nextright;
vv.push_back(vector<int>());
}
}
while(!vv.empty() && vv.back().empty()) vv.pop_back();
return vv;
}
};
上一篇: 110: 平衡二叉树
推荐阅读