题意:
给定一个节点数为 n 二叉树,要求从上到下按层打印二叉树的 val 值,同一层结点从左至右输出,每一层输出一行,将输出的结果存放到一个二维数组中返回。
方法一:
bfs层次遍历
思路:利用队列实现 bfs 层次遍历。重点:计算每一层时,要先记录当前队列的元素个数。(可以实现每层的遍历)之后,将非空的左儿子节点入队,将非空的右儿子节点入队。
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
vector<int> v;
if(pRoot==nullptr)
return res;
queue<TreeNode*> q;//队列
q.push(pRoot);//根节点入队
while(!q.empty()){
int num=q.size();//记录当前队列的元素个数
v.clear();
while(num--){
auto t=q.front();//出队
q.pop();
v.push_back(t->val);
if(t->left){//将非空的左儿子节点入队
q.push(t->left);
}
if(t->right){//将非空的右儿子节点入队
q.push(t->right);
}
}
res.push_back(v);
}
return res;
}
};
时间复杂度:
空间复杂度:![]()
方法二:
dfs 递归
思路:重点:记录每个节点的深度,而每一个的深度对应一个 vector。
因此,可以递归遍历每个节点,记录每个节点的深度。
class Solution {
public:
vector<vector<int>> res;
vector<vector<int> > Print(TreeNode* pRoot) {
dfs(pRoot,1);
return res;
}
void dfs(TreeNode* root,int depth){
if(root==nullptr){
return;
}
if(res.size()<depth){//新建一层
res.push_back(vector<int>());
}
res[depth-1].push_back(root->val);
dfs(root->left,depth+1);//递归左儿子节点
dfs(root->right,depth+1);//递归右儿子节点
}
};
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号