每日一练(19):从上到下打印二叉树
title: 每日一练(19):从上到下打印二叉树
categories:[剑指offer]
tags:[每日一练]
date: 2022/02/15
每日一练(19):从上到下打印二叉树
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
注意的是要把每一层放到一起,需要维护一个level进行保存。
DFS记得使用引用&,不然就得维护一个全局变量了。
方法一:BFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> res;
while (q.size()) {
int size = q.size();
vector<int> level;
for (int i=0;i<size;i++) {
TreeNode* rt = q.front();
q.pop();
if (!rt) {
continue;
}
level.push_back(rt->val);
if (rt->left) {
q.push(rt->left);
}
if (rt->right) {
q.push(rt->right);
}
}
if (level.size()!=NULL) {
res.push_back(level);
}
}
return res;
}
};
方法二:DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
dfs(root, res, 0);
return res;
}
void dfs(TreeNode* root,vector<vector<int>>& res,int level)
{
if (!root) {
return;
}
if (level >= res.size()) {
res.emplace_back(vector<int>());
}
res[level].emplace_back(root->val);
dfs(root->left, res, level+1);
dfs(root->right, res, level+1);
}
};