当前位置:网站首页>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)
边栏推荐
- Oracle 11g "password delayed verification" feature
- PHP连接mysql数据库,数据库连接静态工具类,简化连接。
- Navicat connects to MySQL database on Cloud Server
- ASEMI整流桥GBU1510参数,GBU1510规格,GBU1510封装
- [experience sharing] strong recommendation - screenshot gadget FastStone capture (FSC)
- Summary of basic knowledge of C language pointer (I)
- Hcip day 14
- Apply for SSL certificate, configure SSL certificate for domain name, and deploy server; Download and installation of SSL certificate
- ext4、ntfs、xfs、btrfs、zfs、f2fs和reiserFS性能对比
- sersync/lsync实时同步
猜你喜欢

Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%

线性回归原理推导

5-20v input peak charging current 3.5A single lithium battery switching charging chip sc7101

【程序员必备】七夕表白攻略:”月遇从云,花遇和风,晚上的夜空很美“。(附源码合集)

括号嵌套问题(建议收藏)

Derivation of linear regression principle

Aike AI frontier promotion (7.18)

A 4W word redis interview tutorial

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

Performance comparison of ext4, NTFS, XFS, Btrfs, ZFS, f2fs and ReiserFS
随机推荐
Idea2020.3.1 cannot be opened (double click cannot be opened), but it can be opened through idea.bat.
leetcode-462.最少移动次数使数组元素相等
UE4 how to render statically? 5 steps to generate static rendering
Derivation of linear regression principle
How to choose sentinel vs hystrix?
[experience sharing] strong recommendation - screenshot gadget FastStone capture (FSC)
waf详解
某大厂开发和测试干了一架,还用鼠标线勒脖子...
If you want to do a good job in software testing, you can first understand ast, SCA and penetration testing
KBPC1510-ASEMI大芯片15A整流桥KBPC1510
Zkevm: summary of zkevm and L1 by Mina's CEO
文件上传报错:Current request is not a multipart request
测试工作不受重视?学长:你应该换位思考
Bing(必应)搜索,为什么用户越来越多?
[mathematical modeling - Summary of planning model] | matlab solution
离线数据仓库从0到1-阶段二软件安装
Three ways of redis cluster
网络模型及协议
How Lora wireless gateway can quickly realize end-to-cloud transmission
Summary of basic knowledge of C language pointer (I)