当前位置:网站首页>leetcode: 102. 二叉树的层序遍历
leetcode: 102. 二叉树的层序遍历
2022-07-26 03:39:00 【uncle_ll】
102. 二叉树的层序遍历
来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/binary-tree-level-order-traversal/
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000
解法
- 递归: 给定的node以及层,判断层数是否与结果的长度相同,如果是相同,说明该node应该放入该层中,注意是从第0层开始。
- BFS:层序遍历,使用一个列表维持当前层的节点。当前层的长度来控制遍历的次数,如果有左右子节点,将其加到列表中;
代码实现
递归
python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
levels = []
def helper(node, level):
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
if node.left:
helper(node.left, level+1)
if node.right:
helper(node.right, level+1)
helper(root, 0)
return levels
c++实现
/** * 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 {
vector<vector<int>> res;
public:
void helper(TreeNode* node, int level) {
if (res.size() == level)
res.push_back({
});
res[level].push_back(node->val);
if (node->left)
helper(node->left, level+1);
if (node->right)
helper(node->right, level+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr)
return res;
helper(root, 0);
return res;
}
};
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
BFS
python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
# bfs
if not root:
return []
queue = []
res = []
queue.append(root)
while queue:
level_res = []
for i in range(len(queue)):
node = queue.pop(0)
level_res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level_res)
return res
c++实现
/** * 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 == nullptr)
return {
};
queue<TreeNode*> q;
vector<vector<int>> res;
q.push(root);
while (q.size() != 0) {
vector<int> tmp;
int level_wide = q.size();
for(int i=0; i<level_wide; i++) {
TreeNode* node = q.front();
q.pop();
tmp.push_back(node->val);
if(node->left != nullptr)
q.push(node->left);
if (node->right != nullptr)
q.push(node->right);
}
res.push_back(tmp);
}
return res;
}
};
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n) , 每个点进队出队各一次,故渐进时间复杂度为 O(n)
- 空间复杂度: O ( n ) O(n) O(n), 队列中元素的个数不超过 n 个,故渐进空间复杂度为 O(n)
边栏推荐
- A 4W word redis interview tutorial
- ACM mm 2022 | end to end multi granularity comparative learning for video text retrieval
- 78. Subset
- Leetcode-169. most elements
- 容器跑不动?网络可不背锅
- C语言预处理指令以及Makefile脚本讲解
- Easyexcel sets row hiding to solve the problem of sethidden (true) invalidation
- Multi merchant mall system function disassembly lecture 15 - platform side member label
- 离线数据仓库从0到1-阶段二软件安装
- 开源许可证的传染性问题浅析
猜你喜欢

ue4如何进行静态渲染?5个步骤生成静态渲染

Zkevm: summary of zkevm and L1 by Mina's CEO

Completion report of communication software development and Application

UDP和TCP可以使用同一个端口吗?

Configuration and use of virtualservice, gateway and destinationrule of istio III

赶紧进来!!!用c语言基础知识几十行代码写一个猜数字小游戏

6-40v input fixed 5V 3.3V output 1.1a current 23-5 package

Opencv annotates the image (picture frame + writing)

LoRa和NB-IOT可用用在哪些地方

Multi merchant mall system function disassembly lecture 15 - platform side member label
随机推荐
括号嵌套问题(建议收藏)
ELS callback function, exit message
ELS message loop
基本折线图:最直观呈现数据的趋势和变化
Use VRRP technology to realize gateway equipment redundancy, with detailed configuration experiments
Moco V2: further upgrade of Moco series
Hcip day 14
Day 7 hcip notes sorting (OSPF configuration)
oracle 11g “密码延迟验证”特性
Navicat connects to MySQL database on Cloud Server
Navicat连接云端服务器上的MySQL数据库
div设置高度不生效
Portable power fast charging scheme 30W automatic pressure rise and fall PD fast charging
【 Kotlin 中的类和对象实例】
让百度收录,爬虫自己网站
Where can Lora and nb-iot be used
A 4W word redis interview tutorial
Configuration and use of virtualservice, gateway and destinationrule of istio III
2022-07-21 第四小组 多态
全校软硬件基础设施一站式监控 ,苏州大学以时序数据库替换 PostgreSQL