当前位置:网站首页>Leetcode: 102. Sequence traversal of binary tree
Leetcode: 102. Sequence traversal of binary tree
2022-07-26 03:45:00 【uncle_ ll】
102. Sequence traversal of binary tree
source : Power button (LeetCode)
link : https://leetcode.cn/problems/binary-tree-level-order-traversal/
Give you the root node of the binary tree root , Returns the Sequence traversal . ( That is, layer by layer , Access all nodes from left to right ).

Example 1:
Input :root = [3,9,20,null,null,15,7]
Output :[[3],[9,20],[15,7]]
Example 2:
Input :root = [1]
Output :[[1]]
Example 3:
Input :root = []
Output :[]
Tips :
The number of nodes in the tree is in the range [0, 2000] Inside
-1000 <= Node.val <= 1000
solution
- recursive : A given node And layer , Judge whether the number of layers is the same as the length of the result , If it's the same , Explain the node It should be placed in this layer , Attention is from the 0 Layer start .
- BFS: Sequence traversal , Use a list to maintain the nodes of the current layer . The length of the current layer controls the number of iterations , If there are left and right child nodes , Add it to the list ;
Code implementation
recursive
python Realization
# 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++ Realization
/** * 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;
}
};
Complexity analysis
- Time complexity : O ( n ) O(n) O(n)
- Spatial complexity : O ( n ) O(n) O(n)
BFS
python Realization
# 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++ Realization
/** * 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;
}
};
Complexity analysis
- Time complexity : O ( n ) O(n) O(n) , Enter and leave the team at each point , Therefore, the asymptotic time complexity is O(n)
- Spatial complexity : O ( n ) O(n) O(n), The number of elements in the queue does not exceed n individual , So the asymptotic space complexity is O(n)
边栏推荐
- [programmers must] Tanabata confession strategy: "the moon meets the cloud, the flowers meet the wind, and the night sky is beautiful at night". (with source code Collection)
- ext4、ntfs、xfs、btrfs、zfs、f2fs和reiserFS性能对比
- 【数学建模-规划模型总结】| MATLAB求解
- 6年从零开始的自动化测试之路,开发转测试我不后悔...
- Navicat连接云端服务器上的MySQL数据库
- Can UDP and TCP use the same port?
- 容器跑不动?网络可不背锅
- Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%
- 触觉智能分享-RK3568在景区导览机器人中的应用
- PXE efficient batch network installation
猜你喜欢

文件上传报错:Current request is not a multipart request

easyExcel设置行隐藏,解决setHidden(true)失效问题

触觉智能分享-RK3568在景区导览机器人中的应用

HCIP第十四天

全校软硬件基础设施一站式监控 ,苏州大学以时序数据库替换 PostgreSQL

安装VMware报错failed to install the hcmon driver

What are you interviewing for in a big factory? It's worth watching (I)

How to choose sentinel vs hystrix?

离线数据仓库从0到1-阶段二软件安装

涂鸦幻彩产品开发包如何使用
随机推荐
Hcip day 14
MySQL索引失效场景以及解决方案
Alibaba Sentinel - cluster traffic control
zk-SNARK:关于私钥、环签名、ZKKSP
ELS callback function, exit message
Leetcode-462. make the array elements equal with the minimum number of moves
Leetcode-169. most elements
div设置高度不生效
waf详解
C language preprocessing instructions and makefile script explanation
The convolution kernel is expanded to 51x51, and the new CNN architecture slak counterattacks the transformer
Bing(必应)搜索,为什么用户越来越多?
How to choose sentinel vs hystrix?
JS Base64 encoding and decoding
括号嵌套问题(建议收藏)
Where can Lora and nb-iot be used
sersync/lsync实时同步
[experience sharing] strong recommendation - screenshot gadget FastStone capture (FSC)
JS base64编码和解码
Use VRRP technology to realize gateway equipment redundancy, with detailed configuration experiments